package cn.iocoder.yudao.module.handguard.service.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserAddReqVo;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserAddReqsVo;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserAllocationReqVo;
import cn.iocoder.yudao.module.handguard.controller.admin.client.vo.UserPageReqVO;
import cn.iocoder.yudao.module.handguard.controller.admin.order.vo.MemberUserBaseVO;
import cn.iocoder.yudao.module.handguard.controller.admin.order.vo.UserResVo;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccesspercentage.vo.PercentageVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccessrecord.vo.ProductAccessRecordBaseVO;
import cn.iocoder.yudao.module.handguard.controller.admin.productaccessrecord.vo.ProductAccessRecordCreateReqVO;
import cn.iocoder.yudao.module.handguard.controller.admin.userdb.vo.UserInfoDbVO;
import cn.iocoder.yudao.module.handguard.controller.app.carrecord.vo.CarRecordBaseVO;
import cn.iocoder.yudao.module.handguard.controller.app.carrecord.vo.CarRecordRespVO;
import cn.iocoder.yudao.module.handguard.controller.app.houserecord.vo.HouseRecordRespVO;
import cn.iocoder.yudao.module.handguard.controller.app.user.vo.*;
import cn.iocoder.yudao.module.handguard.convert.carrecord.CarRecordConvert;
import cn.iocoder.yudao.module.handguard.convert.houserecord.HouseRecordConvert;
import cn.iocoder.yudao.module.handguard.convert.product.ProductConvert;
import cn.iocoder.yudao.module.handguard.convert.productaccessrecord.ProductAccessRecordConvert;
import cn.iocoder.yudao.module.handguard.convert.user.MiniUserConvert;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationdeductrecord.ApplicationDeductRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationrecord.ApplicationRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.carrecord.CarRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.houserecord.HouseRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.orderprocessrecord.OrderProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.processrecord.ProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.product.ProductDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccess.ProductAccessDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccessitem.ProductAccessItemDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccesspercentage.ProductAccessPercentageDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccessrecord.ProductAccessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.publicitytype.PublicityTypeDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable1.UserBaseTable1DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable10.UserBaseTable10DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable11.UserBaseTable11DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable12.UserBaseTable12DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable13.UserBaseTable13DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable14.UserBaseTable14DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable15.UserBaseTable15DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable16.UserBaseTable16DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable2.UserBaseTable2DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable3.UserBaseTable3DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable4.UserBaseTable4DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable5.UserBaseTable5DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable6.UserBaseTable6DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable7.UserBaseTable7DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable8.UserBaseTable8DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userbasetable9.UserBaseTable9DO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.usertablesaudit.UserTablesAuditDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationdeductrecord.ApplicationDeductRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationrecord.ApplicationRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.carrecord.CarRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.houserecord.HouseRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.housingresource.HousingResourceMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.orderprocessrecord.OrderProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.processrecord.ProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.product.ProductMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccess.ProductAccessMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccessitem.ProductAccessItemMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccesspercentage.ProductAccessPercentageMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccessrecord.ProductAccessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.publicitytype.PublicityTypeMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.user.MiniUserMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable1.UserBaseTable1Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable10.UserBaseTable10Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable11.UserBaseTable11Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable12.UserBaseTable12Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable13.UserBaseTable13Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable14.UserBaseTable14Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable15.UserBaseTable15Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable16.UserBaseTable16Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable2.UserBaseTable2Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable3.UserBaseTable3Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable4.UserBaseTable4Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable5.UserBaseTable5Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable6.UserBaseTable6Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable7.UserBaseTable7Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable8.UserBaseTable8Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userbasetable9.UserBaseTable9Mapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.usertablesaudit.UserTablesAuditMapper;
import cn.iocoder.yudao.module.handguard.properties.WxLoginVo;
import cn.iocoder.yudao.module.handguard.properties.WxMaConfiguration;
import cn.iocoder.yudao.module.handguard.properties.WxUserVo;
import cn.iocoder.yudao.module.handguard.service.notification.NotificationService;
import cn.iocoder.yudao.module.handguard.service.productaccesspercentage.ProductAccessPercentageService;
import cn.iocoder.yudao.module.handguard.service.usertablesaudit.UserTablesAuditService;
import cn.iocoder.yudao.module.handguard.tool.CalculateUtils;
import cn.iocoder.yudao.module.handguard.tool.DataConversionUtils;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCreateReqDTO;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenRespDTO;
import cn.iocoder.yudao.module.system.enums.logger.LoginLogTypeEnum;
import cn.iocoder.yudao.module.system.enums.logger.LoginResultEnum;
import cn.iocoder.yudao.module.system.enums.oauth2.OAuth2ClientConstants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.doFormat;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * @author: liuweijun
 * @since: 2023/9/11 17:16
 * @description:
 */
@Service
@Validated
@Slf4j
public class MiniUserServiceImpl implements MiniUserService {

    @Resource
    private PublicityTypeMapper publicityTypeMapper;

    @Resource
    private NotificationService notificationService;

    @Resource
    private MiniUserMapper miniUserMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private OAuth2TokenApi oauth2TokenApi;

    @Resource
    private ProductAccessMapper productAccessMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserBaseTable7Mapper table7Mapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CarRecordMapper carRecordMapper;

    @Resource
    private HouseRecordMapper houseRecordMapper;

    @Resource
    private ApplicationRecordMapper applicationRecordMapper;

    @Resource
    private ProductAccessRecordMapper productAccessRecordMapper;

    @Resource
    private ProcessRecordMapper processRecordMapper;

    @Resource
    private ProductAccessPercentageService percentageService;

    @Resource
    private ApplicationDeductRecordMapper deductRecordMapper;

    @Resource
    private UserBaseTable1Mapper userBaseTable1Mapper;
    @Resource
    private UserBaseTable2Mapper userBaseTable2Mapper;
    @Resource
    private UserBaseTable3Mapper userBaseTable3Mapper;
    @Resource
    private UserBaseTable4Mapper userBaseTable4Mapper;
    @Resource
    private UserBaseTable5Mapper userBaseTable5Mapper;
    @Resource
    private UserBaseTable6Mapper userBaseTable6Mapper;
    @Resource
    private UserBaseTable7Mapper userBaseTable7Mapper;
    @Resource
    private UserBaseTable8Mapper userBaseTable8Mapper;
    @Resource
    private UserBaseTable9Mapper userBaseTable9Mapper;
    @Resource
    private UserBaseTable10Mapper userBaseTable10Mapper;
    @Resource
    private UserBaseTable11Mapper userBaseTable11Mapper;
    @Resource
    private UserBaseTable12Mapper userBaseTable12Mapper;
    @Resource
    private UserBaseTable13Mapper userBaseTable13Mapper;
    @Resource
    private UserBaseTable14Mapper userBaseTable14Mapper;

    @Resource
    private UserBaseTable15Mapper userBaseTable15Mapper;

    @Resource
    private UserBaseTable16Mapper userBaseTable16Mapper;

    @Resource
    private UserTablesAuditMapper userTablesAuditMapper;

    @Resource
    private ProductAccessItemMapper productAccessItemMapper;

    @Resource
    private OrderProcessRecordMapper orderProcessRecordMapper;

    @Resource
    private HousingResourceMapper housingResourceMapper;

    @Override
    public PageResult<UserDO> getUserPage(UserPageReqVO pageReqVO) {
        return miniUserMapper.selectPage(pageReqVO);
    }

    @Override
    public MemberUserBaseVO getUserInfo(Long id) {
        MemberUserBaseVO memberUserBaseVO = orderMapper.getUserInfoById(id);
        //车辆信息
        LambdaQueryWrapper<UserBaseTable7DO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserBaseTable7DO::getUserId, id);
        List<UserBaseTable7DO> carList = table7Mapper.selectList(wrapper);
        if (carList.size() > 0) {
            memberUserBaseVO.setCarList(carList);
        }
        return memberUserBaseVO;
    }

    @Override
    public void updateUserAllocationAgent(UserAllocationReqVo reqVo) {
        validateOrderStatus(reqVo.getOrderId());
        applicationRecordMapper.updateAgentByOrderId(reqVo.getAgentId(), reqVo.getOrderId());
    }

    @Override
    public void updateUserAllocationWarrant(UserAllocationReqVo reqVo) {
        validateOrderStatus(reqVo.getOrderId());
        applicationRecordMapper.updateWarrantByOrderId(reqVo.getWarrantId(), reqVo.getOrderId());
    }

    @Override
    public void cancelAllocationWarrant(UserAllocationReqVo reqVo) {
        validateOrderStatus(reqVo.getOrderId());
        applicationRecordMapper.cancelAllocationWarrant(reqVo.getOrderId());
    }

    @Override
    public void cancelAllocationAgent(UserAllocationReqVo reqVo) {
        validateOrderStatus(reqVo.getOrderId());
        applicationRecordMapper.cancelAllocationAgent(reqVo.getOrderId());
    }

    private void validateOrderStatus(Long id) {
        //校验订单是否已完成，如果已经完成，不能分配或取消
        ApplicationRecordDO recordDO = applicationRecordMapper.selectById(id);
        if (recordDO != null) {
            if (recordDO.getApplyState().equals("3")) {
                throw exception(ORDER_STATUS_CHECK);
            }
        }
    }

    @Override
    public String setOperator(Long userId, SetOperatorVo req) {
        ApplicationRecordDO recordDO = applicationRecordMapper.selectOne(
                new LambdaQueryWrapper<ApplicationRecordDO>().eq(ApplicationRecordDO::getId, req.getOrderId()).eq(ApplicationRecordDO::getUserId, userId));
        if (recordDO != null) { //避免模拟请求操作
            recordDO.setAgentId(req.getOperatorId());
            applicationRecordMapper.updateById(recordDO);
            return "设置成功";
        } else {
            return "设置失败，请联系工作人员！";
        }
    }

    @Override
    public boolean updateIdCard(Long userId, UpdateIdCardReqVO reqVo) {
        UserDO agent = miniUserMapper.getUserInfo(userId);
        if (StringUtils.isNotEmpty(agent.getIdentityCard())) {
            if (agent.getIdentityCard().equals(reqVo.getIdCard())) {
                throw exception(ID_CARD_CHECK_AGENT_EXISTS);
            }
        }
        ApplicationRecordDO recordDO = applicationRecordMapper.selectById(reqVo.getOrderId());
        int num = miniUserMapper.checkIdCard(reqVo.getIdCard());
        if (num > 0) {
            throw exception(ID_CARD_EXISTS);
        }

        miniUserMapper.updateIdCard(recordDO.getUserId(), reqVo.getIdCard());

        return true;
    }

    @Override
    @Transactional
    public void updateIsWork(Long id) {
        UserDO u = miniUserMapper.selectById(id);
        u.setUserType("1");//设置成普通用户
        u.setUsername("");
        u.setPassword("");
        miniUserMapper.updateById(u);
        miniUserMapper.deleteUserRole(id);//清除以前权限
    }

    @Override
    @Transactional
    public int addSalesman(UserAddReqVo reqVo) {
        LoginUser user = getLoginUser();
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(reqVo, userDO);
        userDO.setId(reqVo.getUserId());
        if (StringUtils.isNotEmpty(reqVo.getPassword())) {
            userDO.setPassword(encodePassword(reqVo.getPassword())); // 加密密码
        }

        //判断登录名否存在
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername, reqVo.getUsername());
        UserDO u = miniUserMapper.selectOne(queryWrapper);
        if (u != null) {
            throw exception(USERNAME_EXISTS);
        }

        //绑定角色
        Long role = 2l;//普通用户角色
        Long deptId = 0l;
        if (reqVo.getUserType().equals("2")) {
            role = 140l;//固定业务员角色id
        } else if (reqVo.getUserType().equals("3")) {
            role = 141l;//固定权证角色id
        } else if (reqVo.getUserType().equals("5")) {
            role = 1904055947207581698l;//房源业务员
        }

        userDO.setDeptId(deptId);
        int result = miniUserMapper.updateById(userDO);

        //先删除再新增
        miniUserMapper.deleteUserRole(reqVo.getUserId());

        int roles = miniUserMapper.addUserRole(reqVo.getUserId(), role, new Date(), user.getId());

        return roles;
    }


    private AuthLoginRespVo createTokenAfterLoginSuccess(UserDO user) {
        // 插入登陆日志
        //createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(user.getId()).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return MiniUserConvert.INSTANCE.miniConvert(accessTokenRespDTO);
    }

    private AuthLoginRespVo createTokenAfterLoginSuccess(Long userId) {
        // 插入登陆日志
        //createLoginLog(user.getId(), mobile, logType, LoginResultEnum.SUCCESS);
        // 创建 Token 令牌
        OAuth2AccessTokenRespDTO accessTokenRespDTO = oauth2TokenApi.createAccessToken(new OAuth2AccessTokenCreateReqDTO()
                .setUserId(userId).setUserType(getUserType().getValue())
                .setClientId(OAuth2ClientConstants.CLIENT_ID_DEFAULT));
        // 构建返回结果
        return MiniUserConvert.INSTANCE.miniConvert(accessTokenRespDTO);
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.MEMBER;
    }

    @Override
    @Transactional
    public CommonResult<AuthLoginRespVo> login(WxLoginVo reqVO) {
        //AuthLoginRespVo authLoginRespVO = new AuthLoginRespVo();
        //WeChatResVo weChatResVo = new WeChatResVo();
        WxMaService wxMaService = WxMaConfiguration.wxMaService();
        // 获得对应的手机号信息
        WxMaPhoneNumberInfo phoneNumberInfo = null;
        try {
            phoneNumberInfo = wxMaService.getUserService().getNewPhoneNoInfo(reqVO.getPhoneCode());

        } catch (Exception exception) {
            System.out.println(exception.getMessage());
        }

        // 调用微信 API 获取用户的 openid 和 session_key
        WxMaJscode2SessionResult session = null;
        try {
            session = wxMaService.getUserService().getSessionInfo(reqVO.getLoginCode());
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        String openid = session.getOpenid();
        // =============================== 处理业务
        if (StringUtils.isNotEmpty(phoneNumberInfo.getPhoneNumber())) {
            LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserDO::getMobile, phoneNumberInfo.getPhoneNumber());
            UserDO user = miniUserMapper.selectOne(wrapper);
            if (user != null) {
                if (StringUtils.isEmpty(user.getOpenId())) {
                    user.setOpenId(openid);
                    miniUserMapper.updateById(user);
                }
                if (user.getUserType().equals("4")) {//如果后台新增区域经理或业务主管、权证主管设置了手机号，小程序进入了之后避免类型4，所以设置1返回
                    user.setUserType("1");//普通用户浏览
                }
            } else {
                //不存在创建用户
                UserAddReqVo userAddReqVo = new UserAddReqVo();
                userAddReqVo.setUserType("1");
                userAddReqVo.setStatus("0");
                userAddReqVo.setDeptId(1825460330510901250l);//默认
                userAddReqVo.setOpenId(openid);
                userAddReqVo.setMobile(phoneNumberInfo.getPhoneNumber());
                UserDO userDO = new UserDO();
                BeanUtils.copyProperties(userAddReqVo, userDO);
                userDO.setAvatar("https://www.hu-tai.com.cn/minio/349369c3519d5501c2e6b84f018bef2e318b46db76c7be61a97ebf81612c2eb5.png");
                userDO.setSex(3);
                miniUserMapper.insert(userDO);
                userDO.setNickname("用户" + userDO.getId());
                miniUserMapper.updateById(userDO);

                user = miniUserMapper.selectById(userDO.getId());

                if (user != null) {
                    //账号是否禁用
                    if (user.getStatus() == 1) {
                        return CommonResult.error(500, "账号已禁用，无法登录！");
                    }
                }
                //BeanUtils.copyProperties(userDO, user);
                //addSalesman(userAddReqVo);
            }
            //weChatResVo.setSessionKey(session.getSessionKey());
            //weChatResVo.setOpenId(session.getOpenid());
            return CommonResult.success(createTokenAfterLoginSuccess(user));
        } else {
            return CommonResult.error(500, "获取微信手机号信息失败");
        }
    }

    @Override
    public CommonResult<UserPropertyBaseVO> authGetUserInfo(Long userId) {
        UserPropertyBaseVO userPropertyBaseVO = new UserPropertyBaseVO();
        //获取当前用户信息
        try {
            LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserDO::getId, userId);
            UserDO user = miniUserMapper.selectOne(wrapper);
            if (user != null) {
                if (user.getUserType().equals("4")) {//如果后台新增区域经理或业务主管、权证主管设置了手机号，小程序进入了之后避免类型4，所以设置1返回
                    user.setUserType("1");//普通用户浏览
                }
                BeanUtils.copyProperties(user, userPropertyBaseVO);
                //查询房产信息
                LambdaQueryWrapper<HouseRecordDO> houseWrapper = new LambdaQueryWrapper<>();
                houseWrapper.eq(HouseRecordDO::getUserId, userId);
                houseWrapper.orderByDesc(HouseRecordDO::getCreateTime);
                List<HouseRecordRespVO> houseList = HouseRecordConvert.INSTANCE.convertList(houseRecordMapper.selectList(houseWrapper));
                if (houseList.size() <= 0) {
                    houseList = new ArrayList<>();
                }
                userPropertyBaseVO.setHouseList(houseList);

                //查询车辆信息
                LambdaQueryWrapper<CarRecordDO> carWrapper = new LambdaQueryWrapper<>();
                carWrapper.eq(CarRecordDO::getUserId, userId);
                carWrapper.orderByDesc(CarRecordDO::getCreateTime);
                List<CarRecordRespVO> carList = CarRecordConvert.INSTANCE.convertList(carRecordMapper.selectList(carWrapper));
                if (carList.size() <= 0) {
                    carList = new ArrayList<>();
                }
                userPropertyBaseVO.setCarList(carList);

                return CommonResult.success(userPropertyBaseVO);
            } else {
                return CommonResult.error(500, "用户不存在");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    @Override
//    public CommonResult<UserBaseVO> authGetUserInfo(WxUserVo resVo) {
//        //获取微信当前用户头像、呢称等信息
//        try {
//            WxMaService wxMaService = WxMaConfiguration.wxMaService();
//            // 调用微信 API 获取用户的详细信息
//            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(resVo.getSessionKey(), resVo.getEncryptedData(), resVo.getIv());
//            LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(UserDO::getOpenId,resVo.getOpenId());
//            UserDO user =miniUserMapper.selectOne(wrapper);
//            if (user!=null){
//                //空时候才更新
//                if (StringUtils.isEmpty(userInfo.getAvatarUrl())){
//                    user.setAvatar(userInfo.getAvatarUrl());
//                }
//                user.setNickname(userInfo.getNickName());
//                miniUserMapper.updateById(user);
//            }
//            return CommonResult.success(MiniUserConvert.INSTANCE.convert(user));
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

    @Override
    @Transactional
    public int salesmanAddUser(UserAddReqsVo reqVo) {
        //当前操作人
        Long userId = getLoginUser().getId();
        UserDO nUser = miniUserMapper.selectById(userId);
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(reqVo, userDO);
        userDO.setUserType("1");
        userDO.setStatus(0);
        //userDO.setReferrer(userId);
        //userDO.setAgentId(userId);
        userDO.setAgentName(nUser.getName());
        userDO.setAvatar("https://www.hu-tai.com.cn/minio/349369c3519d5501c2e6b84f018bef2e318b46db76c7be61a97ebf81612c2eb5.png");
        //判断是否存在
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getMobile, reqVo.getMobile());
        UserDO u = miniUserMapper.selectOne(queryWrapper);
        if (u != null) {
            throw exception(USER_EXISTS);
        } else {
            miniUserMapper.insert(userDO);
            //更新昵称
            userDO.setNickname("用户" + userDO.getId());
            miniUserMapper.updateById(userDO);
            //添加车子信息
            if (reqVo.getCarList() != null) {
                if (reqVo.getCarList().size() > 0) {
                    List<CarRecordDO> recordDOList = new ArrayList<>();
                    reqVo.getCarList().forEach(c -> {
                        CarRecordDO carRecordDO = new CarRecordDO();
                        BeanUtils.copyProperties(c, carRecordDO);
                        carRecordDO.setUserId(userDO.getId());
                        recordDOList.add(carRecordDO);
                    });
                    carRecordMapper.insertBatch(recordDOList);
                }
            }
            //添加房子信息
            if (reqVo.getHouseList() != null) {
                if (reqVo.getHouseList().size() > 0) {
                    List<HouseRecordDO> houseRecordDOList = new ArrayList<>();
                    reqVo.getHouseList().forEach(h -> {
                        HouseRecordDO houseRecordDO = new HouseRecordDO();
                        BeanUtils.copyProperties(h, houseRecordDO);
                        houseRecordDO.setUserId(userDO.getId());
                        houseRecordDOList.add(houseRecordDO);
                    });
                    houseRecordMapper.insertBatch(houseRecordDOList);
                }
            }
        }

        return 1;
    }

    @Override
    @Transactional
    public int updateUserInfo(UserAddReqsVo reqVo) {
        //当前操作人
        Long userId = getLoginUser().getId();
        UserDO userDO = miniUserMapper.selectById(userId);
        BeanUtils.copyProperties(reqVo, userDO);
        miniUserMapper.updateById(userDO);

        //添加车子信息
        if (reqVo.getCarList().size() > 0) {
            List<CarRecordDO> recordDOList = new ArrayList<>();
            reqVo.getCarList().forEach(c -> {
                CarRecordDO carRecordDO = new CarRecordDO();
                BeanUtils.copyProperties(c, carRecordDO);
                carRecordDO.setUserId(userDO.getId());
                recordDOList.add(carRecordDO);
            });
            carRecordMapper.saveOrUpdateBatch(recordDOList);
        }

        //添加房子信息
        if (reqVo.getHouseList().size() > 0) {
            List<HouseRecordDO> houseRecordDOList = new ArrayList<>();
            reqVo.getHouseList().forEach(h -> {
                HouseRecordDO houseRecordDO = new HouseRecordDO();
                BeanUtils.copyProperties(h, houseRecordDO);
                houseRecordDO.setUserId(userDO.getId());
                houseRecordDOList.add(houseRecordDO);
            });
            houseRecordMapper.saveOrUpdateBatch(houseRecordDOList);
        }
        return 1;
    }


    /**
     * 对密码进行加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    private String encodePassword(String password) {
        return passwordEncoder.encode(password);
    }


    @Override
    public AuthLoginRespVo weixinMiniAppLogin(Long userId) {
        // 创建 Token 令牌，记录登录日志

        return createTokenAfterLoginSuccess(userId);
    }

    @Override
    public List<ProductDO> getAgentProductList(Long userId) {
        List<ProductDO> productDOList = new ArrayList<>();
        UserDO userDO = miniUserMapper.selectById(userId);
        if (userDO != null) {
            if (StringUtils.isNotEmpty(userDO.getCustomLabel())) {
                String[] arrStr = userDO.getCustomLabel().split(",");
                for (String s : arrStr) {
                    LambdaQueryWrapper<ProductDO> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.like(ProductDO::getProductLable, s);
                    List<ProductDO> pList = productMapper.selectList(queryWrapper);
                    productDOList.addAll(pList);
                }
            }
        }
        return productDOList;
    }


    //============================UserEvaluationController业务方法

    @Override
    public Integer getMyLimit(Long userId) {
        try {
            //String number = String.valueOf(reflect(userId));
            return reflect(userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public int reflect(Long userId) throws Exception {
        int userCount = 100;
        UserDO userDO = miniUserMapper.selectById(userId);
        if (userDO != null) {
            if (StringUtils.isEmpty(userDO.getName())) {
                userCount = userCount - 4;
            }
            if (userDO.getSex() == null) {
                userCount = userCount - 4;
            }
            if (userDO.getAge() == null) {
                userCount = userCount - 4;
            }
            if (StringUtils.isEmpty(userDO.getCensusRegister())) {
                userCount = userCount - 4;
            }
            if (StringUtils.isEmpty(userDO.getRegisteredHk())) {
                userCount = userCount - 4;
            }
            //房产
//        LambdaQueryWrapper<HouseRecordDO> houseQueryWrapper = new LambdaQueryWrapper<>();
//        houseQueryWrapper.eq(HouseRecordDO::getUserId,userId);
//        Long house = houseRecordMapper.selectCount(houseQueryWrapper);
//        if (house!=null){
//            userCount = userCount+25;
//        }
//        //车子
//        LambdaQueryWrapper<CarRecordDO> carQueryWrapper = new LambdaQueryWrapper<>();
//        carQueryWrapper.eq(CarRecordDO::getUserId,userId);
//        Long car = carRecordMapper.selectCount(carQueryWrapper);
//        if (car!=null){
//            userCount =userCount+25;
//        }

            //查询16个表
//            List<UserBaseTable1DO> u1 = userBaseTable1Mapper.selectCount("user_id",userId);
//            List<UserBaseTable2DO> u2 = userBaseTable2Mapper.selectCount();
//            List<UserBaseTable3DO> u3 = userBaseTable3Mapper.selectCount();
//            List<UserBaseTable4DO> u4 = userBaseTable4Mapper.selectCount();
//            List<UserBaseTable5DO> u5 = userBaseTable5Mapper.selectCount();
//            List<UserBaseTable6DO> u6 = userBaseTable6Mapper.selectCount();
//            List<UserBaseTable7DO> u7 = userBaseTable7Mapper.selectCount();
//            List<UserBaseTable8DO> u8 = userBaseTable8Mapper.selectCount();
//            List<UserBaseTable9DO> u9 = userBaseTable9Mapper.selectCount();
//            List<UserBaseTable10DO> u10 = userBaseTable10Mapper.selectCount();
//            List<UserBaseTable11DO> u11 = userBaseTable11Mapper.selectCount();
//            List<UserBaseTable12DO> u12 = userBaseTable12Mapper.selectCount();
//            List<UserBaseTable13DO> u13 = userBaseTable13Mapper.selectCount();
//            List<UserBaseTable14DO> u14 = userBaseTable14Mapper.selectCount();
//            List<UserBaseTable15DO> u15 = userBaseTable15Mapper.selectCount();
//            List<UserBaseTable16DO> u16 = userBaseTable16Mapper.selectCount();
            Long u1 = userBaseTable1Mapper.selectCount("user_id", userId);
            Long u2 = userBaseTable2Mapper.selectCount("user_id", userId);
            Long u3 = userBaseTable3Mapper.selectCount("user_id", userId);
            Long u4 = userBaseTable4Mapper.selectCount("user_id", userId);
            Long u5 = userBaseTable5Mapper.selectCount("user_id", userId);
            Long u6 = userBaseTable6Mapper.selectCount("user_id", userId);
            Long u7 = userBaseTable7Mapper.selectCount("user_id", userId);
            Long u8 = userBaseTable8Mapper.selectCount("user_id", userId);
            Long u9 = userBaseTable9Mapper.selectCount("user_id", userId);
            Long u10 = userBaseTable10Mapper.selectCount("user_id", userId);
            Long u11 = userBaseTable11Mapper.selectCount("user_id", userId);
            Long u12 = userBaseTable12Mapper.selectCount("user_id", userId);
            Long u13 = userBaseTable13Mapper.selectCount("user_id", userId);
            Long u14 = userBaseTable14Mapper.selectCount("user_id", userId);
            Long u15 = userBaseTable15Mapper.selectCount("user_id", userId);
            Long u16 = userBaseTable16Mapper.selectCount("user_id", userId);

            if (u1 <= 0l) {
                userCount = userCount - 5;
            }
            if (u2 <= 0l) {
                userCount = userCount - 5;
            }
            if (u3 <= 0l) {
                userCount = userCount - 5;
            }
            if (u4 <= 0l) {
                userCount = userCount - 5;
            }
            if (u5 <= 0l) {
                userCount = userCount - 5;
            }
            if (u6 <= 0l) {
                userCount = userCount - 5;
            }
            if (u7 <= 0l) {
                userCount = userCount - 5;
            }
            if (u8 <= 0l) {
                userCount = userCount - 5;
            }
            if (u9 <= 0l) {
                userCount = userCount - 5;
            }
            if (u10 <= 0l) {
                userCount = userCount - 5;
            }
            if (u11 <= 0l) {
                userCount = userCount - 5;
            }
            if (u12 <= 0l) {
                userCount = userCount - 5;
            }
            if (u13 <= 0l) {
                userCount = userCount - 5;
            }
            if (u14 <= 0l) {
                userCount = userCount - 5;
            }
            if (u15 <= 0l) {
                userCount = userCount - 5;
            }
            if (u16 <= 0l) {
                userCount = userCount - 5;
            }
        }
        return userCount;
    }


    @Override
    public MyTestResVo getMyTest(Long userId) {
        MyTestResVo resVo = new MyTestResVo();
        List<ProductDO> product = new ArrayList<>();
        BigDecimal countAmount = new BigDecimal(0.0);
        //额度测试匹配
        //房产
        //LambdaQueryWrapper<HouseRecordDO> houseQueryWrapper = new LambdaQueryWrapper<>();
        //houseQueryWrapper.eq(HouseRecordDO::getUserId, userId);
        //Long house = houseRecordMapper.selectCount(houseQueryWrapper);
        //if (house != 0) {
        //    //查找房贷产品
        //    LambdaQueryWrapper<ProductDO> hQueryWrapper = new LambdaQueryWrapper<>();
        //    hQueryWrapper.and(m -> m.eq(ProductDO::getProductName, "房产").
        //            or().eq(ProductDO::getProductName, "房贷"));
        //    List<ProductDO> productDOList = productMapper.selectList(hQueryWrapper);
        //    product.addAll(productDOList);
        //}
        ////车子
        //LambdaQueryWrapper<CarRecordDO> carQueryWrapper = new LambdaQueryWrapper<>();
        //carQueryWrapper.eq(CarRecordDO::getUserId, userId);
        //Long car = carRecordMapper.selectCount(carQueryWrapper);
        //if (car != 0) {
        //    //查找车贷产品
        //    LambdaQueryWrapper<ProductDO> hQueryWrapper = new LambdaQueryWrapper<>();
        //    hQueryWrapper.like(ProductDO::getProductName, "车贷");
        //    hQueryWrapper.or().eq(ProductDO::getProductType, 7);
        //    List<ProductDO> productDOList = productMapper.selectList(hQueryWrapper);
        //    product.addAll(productDOList);
        //}

        //保单贷
        Long u1 = userBaseTable1Mapper.selectCount("user_id", userId);
        if (u1 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("按揭房信贷", 1));
        }

        //保单贷
        Long u2 = userBaseTable2Mapper.selectCount("user_id", userId);
        if (u2 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("保单贷", 2));
        }
        //个人贴息贷款
        Long u3 = userBaseTable3Mapper.selectCount("user_id", userId);
        if (u3 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("个人贴息贷", 3));
        }
        //工薪贷
        Long u4 = userBaseTable4Mapper.selectCount("user_id", userId);
        if (u4 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("工薪贷", 4));
        }
        //公积金贷
        Long u5 = userBaseTable5Mapper.selectCount("user_id", userId);
        if (u5 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("公积金贷", 5));
        }
        //企业贴息贷款
        Long u6 = userBaseTable6Mapper.selectCount("user_id", userId);
        if (u6 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("企业贴息贷款", 6));
        }
        //全款车按揭车信贷资料
        Long u7 = userBaseTable7Mapper.selectCount("user_id", userId);
        if (u7 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("车贷", 7));
        }
        //商业商住楼写字楼厂房一抵押
        Long u8 = userBaseTable8Mapper.selectCount("user_id", userId);
        if (u8 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("商业商住楼写字楼厂房一抵押", 8));
        }
        //商业商住楼写字楼二次抵押
        Long u9 = userBaseTable9Mapper.selectCount("user_id", userId);
        if (u9 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("商业商住楼写字楼二次抵押", 9));
        }
        //商业写字楼按揭贷款
        Long u10 = userBaseTable10Mapper.selectCount("user_id", userId);
        if (u10 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("商业写字楼按揭贷款", 10));
        }
        //税贷
        Long u11 = userBaseTable11Mapper.selectCount("user_id", userId);
        if (u11 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("税贷", 11));
        }
        //企业流水贷
        Long u12 = userBaseTable12Mapper.selectCount("user_id", userId);
        if (u12 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("企业流水贷", 12));
        }
        //企业发票贷
        Long u13 = userBaseTable13Mapper.selectCount("user_id", userId);
        if (u13 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("企业发票贷", 13));
        }
        //住宅按揭贷款
        Long u14 = userBaseTable14Mapper.selectCount("user_id", userId);
        if (u14 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("住宅按揭贷", 14));
        }
        //住宅抵押
        Long u15 = userBaseTable15Mapper.selectCount("user_id", userId);
        if (u15 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("住宅抵押", 15));
        }
        //住宅二次抵押
        Long u16 = userBaseTable16Mapper.selectCount("user_id", userId);
        if (u16 > 0l) {
            //查找产品
            product.addAll(getCommProductByNameAndTypeId("住宅二次抵押", 16));
        }


        if (product.size() > 0) {
            ArrayList<ProductDO> collect = product.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(ProductDO::getId)
            )), ArrayList::new));

            product = collect;

            for (ProductDO productDO : product) {
                PublicityTypeDO publicityTypeDO = publicityTypeMapper.selectById(productDO.getProductType());
                if (publicityTypeDO!=null){
                    productDO.setProductTypeName(publicityTypeDO.getTypeNames());
                }
            }
        }

        //额度
        BigDecimal zero = new BigDecimal(0.0);
        if (product.size() > 0) {
            for (ProductDO p : product) {
                String amount = "0.0";
                //BigDecimal pAmount = new BigDecimal(p.getMaxAmount());
                //额度
                if (p.getProductType() == 1) {
                    LambdaQueryWrapperX<UserBaseTable1DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable1DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable1DO::getCreateTime).last("LIMIT 1");
                    // 限制结果为1条，即最新的一条
                    List<UserBaseTable1DO> table1DOS = userBaseTable1Mapper.selectList(queryWrapper);
                    if (table1DOS.size() > 0) {
                        UserBaseTable1DO userBaseTable1DO = table1DOS.get(0);
                        amount = CalculateUtils.calculateTable1(userBaseTable1DO, p);
                    }
                } else if (p.getProductType() == 2) {
                    LambdaQueryWrapperX<UserBaseTable2DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable2DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable2DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable2DO> table2DOS = userBaseTable2Mapper.selectList(queryWrapper);
                    if (table2DOS.size() > 0) {
                        UserBaseTable2DO table2DO = table2DOS.get(0);
                        amount = CalculateUtils.calculateTable2(table2DO, p);
                    }
                } else if (p.getProductType() == 3) {
                    //暂无
                    amount = CalculateUtils.calculateTable3();
                } else if (p.getProductType() == 4) {
                    LambdaQueryWrapperX<UserBaseTable4DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable4DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable4DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable4DO> table4DOS = userBaseTable4Mapper.selectList(queryWrapper);
                    if (table4DOS.size() > 0) {
                        UserBaseTable4DO table4DO = table4DOS.get(0);
                        amount = CalculateUtils.calculateTable4(table4DO, p);
                    }
                } else if (p.getProductType() == 5) {
                    LambdaQueryWrapperX<UserBaseTable5DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable5DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable5DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable5DO> table5DOS = userBaseTable5Mapper.selectList(queryWrapper);
                    if (table5DOS.size() > 0) {
                        UserBaseTable5DO table5DO = table5DOS.get(0);
                        amount = CalculateUtils.calculateTable5(table5DO, p);
                    }
                } else if (p.getProductType() == 6) {
                    LambdaQueryWrapperX<UserBaseTable6DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable6DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable6DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable6DO> table6DOS = userBaseTable6Mapper.selectList(queryWrapper);
                    if (table6DOS.size() > 0) {
                        UserBaseTable6DO table6DO = table6DOS.get(0);
                        amount = CalculateUtils.calculateTable6(table6DO);
                    }
                } else if (p.getProductType() == 7) {
                    LambdaQueryWrapperX<UserBaseTable7DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable7DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable7DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable7DO> table7DOS = userBaseTable7Mapper.selectList(queryWrapper);
                    if (table7DOS.size() > 0) {
                        UserBaseTable7DO table7DO = table7DOS.get(0);
                        amount = CalculateUtils.calculateTable7(table7DO, p);
                    }
                } else if (p.getProductType() == 8) {
                    LambdaQueryWrapperX<UserBaseTable8DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable8DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable8DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable8DO> table8DOS = userBaseTable8Mapper.selectList(queryWrapper);
                    if (table8DOS.size() > 0) {
                        UserBaseTable8DO table8DO = table8DOS.get(0);
                        amount = CalculateUtils.calculateTable8(table8DO, p);
                    }
                } else if (p.getProductType() == 9) {
                    LambdaQueryWrapperX<UserBaseTable9DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable9DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable9DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable9DO> table9DOS = userBaseTable9Mapper.selectList(queryWrapper);
                    if (table9DOS.size() > 0) {
                        UserBaseTable9DO table9DO = table9DOS.get(0);
                        amount = CalculateUtils.calculateTable9(table9DO, p);
                    }
                } else if (p.getProductType() == 10) {
                    LambdaQueryWrapperX<UserBaseTable10DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable10DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable10DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable10DO> table10DOS = userBaseTable10Mapper.selectList(queryWrapper);
                    if (table10DOS.size() > 0) {
                        UserBaseTable10DO table10DO = table10DOS.get(0);
                        amount = CalculateUtils.calculateTable10(table10DO, p);
                    }
                } else if (p.getProductType() == 11) {
                    LambdaQueryWrapperX<UserBaseTable11DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable11DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable11DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable11DO> table11DOS = userBaseTable11Mapper.selectList(queryWrapper);
                    if (table11DOS.size() > 0) {
                        UserBaseTable11DO table11DO = table11DOS.get(0);
                        amount = CalculateUtils.calculateTable11(table11DO, p);
                    }
                } else if (p.getProductType() == 12) {
                    LambdaQueryWrapperX<UserBaseTable12DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable12DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable12DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable12DO> table12DOS = userBaseTable12Mapper.selectList(queryWrapper);
                    if (table12DOS.size() > 0) {
                        UserBaseTable12DO table12DO = table12DOS.get(0);
                        amount = CalculateUtils.calculateTable12(table12DO, p);
                    }
                } else if (p.getProductType() == 13) {
                    LambdaQueryWrapperX<UserBaseTable13DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable13DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable13DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable13DO> table13DOS = userBaseTable13Mapper.selectList(queryWrapper);
                    if (table13DOS.size() > 0) {
                        UserBaseTable13DO table13DO = table13DOS.get(0);
                        amount = CalculateUtils.calculateTable13(table13DO, p);
                    }
                } else if (p.getProductType() == 14) {
                    LambdaQueryWrapperX<UserBaseTable14DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable14DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable14DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable14DO> table14DOS = userBaseTable14Mapper.selectList(queryWrapper);
                    if (table14DOS.size() > 0) {
                        UserBaseTable14DO table14DO = table14DOS.get(0);
                        amount = CalculateUtils.calculateTable14(table14DO, p);
                    }
                } else if (p.getProductType() == 15) {
                    LambdaQueryWrapperX<UserBaseTable15DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable15DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable15DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable15DO> table15DOS = userBaseTable15Mapper.selectList(queryWrapper);
                    if (table15DOS.size() > 0) {
                        UserBaseTable15DO table15DO = table15DOS.get(0);
                        amount = CalculateUtils.calculateTable15(table15DO, p);
                    }
                } else if (p.getProductType() == 16) {
                    LambdaQueryWrapperX<UserBaseTable16DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable16DO::getUserId, userId);
                    queryWrapper.orderByDesc(UserBaseTable16DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable16DO> table16DOS = userBaseTable16Mapper.selectList(queryWrapper);
                    if (table16DOS.size() > 0) {
                        UserBaseTable16DO table16DO = table16DOS.get(0);
                        amount = CalculateUtils.calculateTable16(table16DO, p);
                    }
                }
                p.setYgMaxAmount(amount);
                //if (!amount.contains("—")){
                //    BigDecimal n = new BigDecimal(amount);
                //    if (n.compareTo(zero) == 0 ){
                //        p.setYgMaxAmount("0.0");
                //    }else if (n.compareTo(BigDecimal.ZERO) < 0) {
                //        p.setYgMaxAmount("0.0");
                //    }else {
                //        p.setYgMaxAmount(amount);
                //    }
                //}else {
                //    p.setYgMaxAmount(amount);
                //}
            }
        }

        resVo.setAmount("");
        resVo.setProductList(ProductConvert.INSTANCE.convertList(product));
        return resVo;
    }

    //公共通用查询方法
    public List<ProductDO> getCommProductByNameAndTypeId(String productName, Integer typeId) {
        LambdaQueryWrapper<ProductDO> hQueryWrapper = new LambdaQueryWrapper<>();
        //hQueryWrapper.like(ProductDO::getProductName, productName);
        //hQueryWrapper.or().eq(ProductDO::getProductType, typeId);
        hQueryWrapper.eq(ProductDO::getStatus, 0);
        hQueryWrapper.eq(ProductDO::getProductType, typeId);
        List<ProductDO> productDOList = productMapper.selectList(hQueryWrapper);
        return productDOList;
    }

    @Override
    @Transactional
    public ApplyForProductResVo applyForProduct(ApplyForProductReqsVo vo) {
        ApplyForProductResVo resVo = new ApplyForProductResVo();
        //当前用户信息
        UserDO userDO = miniUserMapper.selectById(vo.getUserId());

        //判断是否重复申请
        //if (vo.getId().contains(",")) {
        //    String[] pidArr = vo.getId().split(",");
        //    for (String id : pidArr) {
        //        LambdaQueryWrapper<ApplicationRecordDO> queryWrapper = new LambdaQueryWrapper<>();
        //        queryWrapper.eq(ApplicationRecordDO::getUserId, vo.getUserId());
        //        queryWrapper.eq(ApplicationRecordDO::getProductId, id);
        //        queryWrapper.in(ApplicationRecordDO::getApplyState, 1,2);
        //        Long count = applicationRecordMapper.selectCount(queryWrapper);
        //        if (count > 0) {
        //            resVo.setFlag(false);
        //            resVo.setVoList(new ArrayList<>());
        //            return resVo;
        //            //throw exception(USER_APP_RECORD_IS_EXISTS);
        //        }
        //    }
        //} else {
        //    LambdaQueryWrapper<ApplicationRecordDO> queryWrapper = new LambdaQueryWrapper<>();
        //    queryWrapper.eq(ApplicationRecordDO::getUserId, vo.getUserId());
        //    queryWrapper.eq(ApplicationRecordDO::getProductId, vo.getId());
        //    queryWrapper.in(ApplicationRecordDO::getApplyState, 1,2);
        //    Long count = applicationRecordMapper.selectCount(queryWrapper);
        //    if (count > 0) {
        //        resVo.setFlag(false);
        //        resVo.setVoList(new ArrayList<>());
        //        return resVo;
        //        //throw exception(USER_APP_RECORD_IS_EXISTS);
        //    }
        //}

        Long agentId = 0l;
        //如果当前用户存在推荐人，找对推荐人的上级（前提推荐人不是业务员，如果推荐人就是业务员则不找））。
        //默认循环20层，如果找到立马结束循环
        List<AgentUserResVo> resList = new ArrayList<>();
        //业务员团队
        List<AgentUserResVo> voList = miniUserMapper.getAgentList();
        if (userDO.getReferrer() == null) { //业务员团队
            resList.addAll(voList);
        } else {
            Long r = userDO.getReferrer();
            UserDO user = miniUserMapper.selectById(r);
            if (user != null) {
                if (user.getUserType().equals("2")) {
                    AgentUserResVo agentUser = new AgentUserResVo();
                    BeanUtils.copyProperties(user, agentUser);
                    agentId = user.getId();
                    resList.add(agentUser);
                } else {
                    //当前用户是否有推荐人（上级）
                    UserDO u = new UserDO();
                    if (user.getReferrer() != null) {
                        r = user.getReferrer();
                        //取最接近的业务员
                        endLoop:
                        for (int i = 0; i < 20; i++) {
                            if (i == 0) {
                                u = miniUserMapper.selectById(r);
                                if (u.getUserType().equals("2")) {
                                    AgentUserResVo agentUser = new AgentUserResVo();
                                    BeanUtils.copyProperties(u, agentUser);
                                    agentId = agentUser.getId();
                                    resList.add(agentUser);
                                    break endLoop;
                                }
                            } else {
                                if (u.getReferrer() != null) {
                                    u = miniUserMapper.selectById(u.getReferrer());
                                    if (u.getUserType().equals("2")) {
                                        AgentUserResVo agentUser = new AgentUserResVo();
                                        BeanUtils.copyProperties(user, agentUser);
                                        agentId = agentUser.getId();
                                        resList.add(agentUser);
                                        break endLoop;
                                    }
                                }
                            }
                        }
                    }
                    //如果还是没找到展示业务员团队
                    if (resList.size() <= 0) {
                        resList.addAll(voList);
                    }
                }
            } else {
                resList.addAll(voList);
            }
        }

//        Long agentId = 0L;
//        List<AgentUserResVo> resList = new ArrayList<>();
//        //业务员团队
//        List<AgentUserResVo> voList = miniUserMapper.getAgentList();
//
//        if (userDO.getReferrer() == null) {
//            resList.addAll(voList);
//        } else {
//            Long referrerId = userDO.getReferrer();
//            UserDO referrer = miniUserMapper.selectById(referrerId);
//            if (referrer != null) {
//                //推荐人是业务员
//                if ("2".equals(referrer.getUserType())) {
//                    agentId = referrer.getId();
//                    resList.add(convertToAgentUserResVo(referrer));
//                } else {
//                    agentId = findNearestAgent(referrer);
//                    if (agentId == 0L) {
//                        resList.addAll(voList);
//                    } else {
//                        resList.add(convertToAgentUserResVo(miniUserMapper.selectById(agentId)));
//                    }
//                }
//            } else {
//                resList.addAll(voList);
//            }
//        }

//        String[] ids = vo.getId().split(",");
//        BigDecimal maxAmount = new BigDecimal(0.0);
//        for (String id : ids) {
//            //查询产品
//            ProductDO productDO = productMapper.selectById(id);
//            maxAmount = maxAmount.add(new BigDecimal(productDO.getMaxAmount()));
//        }

        //用户完善资料度
        //Integer degree  = getMyLimit(userDO.getId());

        //写入用户申请记录
        ApplicationRecordDO recordDO = new ApplicationRecordDO();
        recordDO.setUserId(vo.getUserId());
        recordDO.setAmount(vo.getAmount());
        recordDO.setWhether(vo.getType());
        recordDO.setApplyState("1");
        recordDO.setProductId(vo.getId());
        recordDO.setIssuanceTime(LocalDateTime.now());
        recordDO.setFlowN("4");//设置为业务员处理
        applicationRecordMapper.insert(recordDO);
        if (agentId > 0l) {
            recordDO.setAgentId(agentId);
            applicationRecordMapper.updateById(recordDO);
        }

        //公式表资料绑定订单 id
        ProductDO productDO = productMapper.selectById(vo.getId());
        if (productDO != null) {
            bdTableIdByType(productDO.getProductType(), vo, recordDO.getId());
        }

        //流程记录
        ProcessRecordDO processRecordDO = new ProcessRecordDO();
        processRecordDO.setFlowN("4");
        processRecordDO.setUserId(vo.getUserId());
        processRecordDO.setApplicationId(recordDO.getId());
        processRecordDO.setIsFail("0");//待审核
        processRecordMapper.insert(processRecordDO);

        resVo.setFlag(true);
        resVo.setOrderId(recordDO.getId());
        resVo.setVoList(resList);

        return resVo;
    }

    private Long findNearestAgent(UserDO user) {
        for (int i = 0; i < 30 && user.getReferrer() != null; i++) {
            user = miniUserMapper.selectById(user.getReferrer());
            if ("2".equals(user.getUserType())) {
                return user.getId();
            }
        }
        return 0L;
    }

    private AgentUserResVo convertToAgentUserResVo(UserDO user) {
        AgentUserResVo agentUser = new AgentUserResVo();
        BeanUtils.copyProperties(user, agentUser);
        return agentUser;
    }

    //关联订单
    public void bdTableIdByType(Integer productType, ApplyForProductReqsVo vo, Long applicationId) {
        if (productType == 1) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable1DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable1DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable1DO::getCreateTime).last("LIMIT 1");
                UserBaseTable1DO table1DO = userBaseTable1Mapper.selectOne(queryWrapper);
                table1DO.setId(null);
                table1DO.setCreateTime(LocalDateTime.now());
                table1DO.setUpdateTime(LocalDateTime.now());
                table1DO.setApplicationId(applicationId);
                userBaseTable1Mapper.insert(table1DO);
            } else {
                UserBaseTable1DO table1DO = userBaseTable1Mapper.selectById(vo.getTableId());
                table1DO.setApplicationId(applicationId);
                userBaseTable1Mapper.updateById(table1DO);
            }
        } else if (productType == 2) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable2DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable2DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable2DO::getCreateTime).last("LIMIT 1");
                UserBaseTable2DO table2DO = userBaseTable2Mapper.selectOne(queryWrapper);
                table2DO.setId(null);
                table2DO.setCreateTime(LocalDateTime.now());
                table2DO.setUpdateTime(LocalDateTime.now());
                table2DO.setApplicationId(applicationId);
                userBaseTable2Mapper.insert(table2DO);
            } else {
                UserBaseTable2DO table2DO = userBaseTable2Mapper.selectById(vo.getTableId());
                table2DO.setApplicationId(applicationId);
                userBaseTable2Mapper.updateById(table2DO);
            }
        } else if (productType == 3) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable3DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable3DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable3DO::getCreateTime).last("LIMIT 1");
                UserBaseTable3DO table3DO = userBaseTable3Mapper.selectOne(queryWrapper);
                table3DO.setId(null);
                table3DO.setCreateTime(LocalDateTime.now());
                table3DO.setUpdateTime(LocalDateTime.now());
                table3DO.setApplicationId(applicationId);
                userBaseTable3Mapper.insert(table3DO);
            } else {
                UserBaseTable3DO table3DO = userBaseTable3Mapper.selectById(vo.getTableId());
                table3DO.setApplicationId(applicationId);
                userBaseTable3Mapper.updateById(table3DO);
            }
        } else if (productType == 4) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable4DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable4DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable4DO::getCreateTime).last("LIMIT 1");
                UserBaseTable4DO table4DO = userBaseTable4Mapper.selectOne(queryWrapper);
                table4DO.setId(null);
                table4DO.setCreateTime(LocalDateTime.now());
                table4DO.setUpdateTime(LocalDateTime.now());
                table4DO.setApplicationId(applicationId);
                userBaseTable4Mapper.insert(table4DO);
            } else {
                UserBaseTable4DO table4DO = userBaseTable4Mapper.selectById(vo.getTableId());
                table4DO.setApplicationId(applicationId);
                userBaseTable4Mapper.updateById(table4DO);
            }
        } else if (productType == 5) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable5DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable5DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable5DO::getCreateTime).last("LIMIT 1");
                UserBaseTable5DO table5DO = userBaseTable5Mapper.selectOne(queryWrapper);
                table5DO.setId(null);
                table5DO.setCreateTime(LocalDateTime.now());
                table5DO.setUpdateTime(LocalDateTime.now());
                table5DO.setApplicationId(applicationId);
                userBaseTable5Mapper.insert(table5DO);
            } else {
                UserBaseTable5DO table5DO = userBaseTable5Mapper.selectById(vo.getTableId());
                table5DO.setApplicationId(applicationId);
                userBaseTable5Mapper.updateById(table5DO);
            }
        } else if (productType == 6) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable6DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable6DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable6DO::getCreateTime).last("LIMIT 1");
                UserBaseTable6DO table6DO = userBaseTable6Mapper.selectOne(queryWrapper);
                table6DO.setId(null);
                table6DO.setCreateTime(LocalDateTime.now());
                table6DO.setUpdateTime(LocalDateTime.now());
                table6DO.setApplicationId(applicationId);
                userBaseTable6Mapper.insert(table6DO);
            } else {
                UserBaseTable6DO table6DO = userBaseTable6Mapper.selectById(vo.getTableId());
                table6DO.setApplicationId(applicationId);
                userBaseTable6Mapper.updateById(table6DO);
            }
        } else if (productType == 7) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable7DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable7DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable7DO::getCreateTime).last("LIMIT 1");
                UserBaseTable7DO table7DO = userBaseTable7Mapper.selectOne(queryWrapper);
                table7DO.setId(null);
                table7DO.setCreateTime(LocalDateTime.now());
                table7DO.setUpdateTime(LocalDateTime.now());
                table7DO.setApplicationId(applicationId);
                userBaseTable7Mapper.insert(table7DO);
            } else {
                UserBaseTable7DO table7DO = userBaseTable7Mapper.selectById(vo.getTableId());
                table7DO.setApplicationId(applicationId);
                userBaseTable7Mapper.updateById(table7DO);
            }
        } else if (productType == 8) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable8DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable8DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable8DO::getCreateTime).last("LIMIT 1");
                UserBaseTable8DO table8DO = userBaseTable8Mapper.selectOne(queryWrapper);
                table8DO.setId(null);
                table8DO.setCreateTime(LocalDateTime.now());
                table8DO.setUpdateTime(LocalDateTime.now());
                table8DO.setApplicationId(applicationId);
                userBaseTable8Mapper.insert(table8DO);
            } else {
                UserBaseTable8DO table8DO = userBaseTable8Mapper.selectById(vo.getTableId());
                table8DO.setApplicationId(applicationId);
                userBaseTable8Mapper.updateById(table8DO);
            }
        } else if (productType == 9) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable9DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable9DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable9DO::getCreateTime).last("LIMIT 1");
                UserBaseTable9DO table9DO = userBaseTable9Mapper.selectOne(queryWrapper);
                table9DO.setId(null);
                table9DO.setCreateTime(LocalDateTime.now());
                table9DO.setUpdateTime(LocalDateTime.now());
                table9DO.setApplicationId(applicationId);
                userBaseTable9Mapper.insert(table9DO);
            } else {
                UserBaseTable9DO table9DO = userBaseTable9Mapper.selectById(vo.getTableId());
                table9DO.setApplicationId(applicationId);
                userBaseTable9Mapper.updateById(table9DO);
            }
        } else if (productType == 10) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable10DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable10DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable10DO::getCreateTime).last("LIMIT 1");
                UserBaseTable10DO table10DO = userBaseTable10Mapper.selectOne(queryWrapper);
                table10DO.setId(null);
                table10DO.setCreateTime(LocalDateTime.now());
                table10DO.setUpdateTime(LocalDateTime.now());
                table10DO.setApplicationId(applicationId);
                userBaseTable10Mapper.insert(table10DO);
            } else {
                UserBaseTable10DO table10DO = userBaseTable10Mapper.selectById(vo.getTableId());
                table10DO.setApplicationId(applicationId);
                userBaseTable10Mapper.updateById(table10DO);
            }
        } else if (productType == 11) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable11DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable11DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable11DO::getCreateTime).last("LIMIT 1");
                UserBaseTable11DO table11DO = userBaseTable11Mapper.selectOne(queryWrapper);
                table11DO.setId(null);
                table11DO.setCreateTime(LocalDateTime.now());
                table11DO.setUpdateTime(LocalDateTime.now());
                table11DO.setApplicationId(applicationId);
                userBaseTable11Mapper.insert(table11DO);
            } else {
                UserBaseTable11DO table11DO = userBaseTable11Mapper.selectById(vo.getTableId());
                table11DO.setApplicationId(applicationId);
                userBaseTable11Mapper.updateById(table11DO);
            }
        } else if (productType == 12) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable12DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable12DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable12DO::getCreateTime).last("LIMIT 1");
                UserBaseTable12DO table12DO = userBaseTable12Mapper.selectOne(queryWrapper);
                table12DO.setId(null);
                table12DO.setCreateTime(LocalDateTime.now());
                table12DO.setUpdateTime(LocalDateTime.now());
                table12DO.setApplicationId(applicationId);
                userBaseTable12Mapper.insert(table12DO);
            } else {
                UserBaseTable12DO table12DO = userBaseTable12Mapper.selectById(vo.getTableId());
                table12DO.setApplicationId(applicationId);
                userBaseTable12Mapper.updateById(table12DO);
            }
        } else if (productType == 13) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable13DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable13DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable13DO::getCreateTime).last("LIMIT 1");
                UserBaseTable13DO table13DO = userBaseTable13Mapper.selectOne(queryWrapper);
                table13DO.setId(null);
                table13DO.setCreateTime(LocalDateTime.now());
                table13DO.setUpdateTime(LocalDateTime.now());
                table13DO.setApplicationId(applicationId);
                userBaseTable13Mapper.insert(table13DO);
            } else {
                UserBaseTable13DO table13DO = userBaseTable13Mapper.selectById(vo.getTableId());
                table13DO.setApplicationId(applicationId);
                userBaseTable13Mapper.updateById(table13DO);
            }
        } else if (productType == 14) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable14DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable14DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable14DO::getCreateTime).last("LIMIT 1");
                UserBaseTable14DO table14DO = userBaseTable14Mapper.selectOne(queryWrapper);
                table14DO.setId(null);
                table14DO.setCreateTime(LocalDateTime.now());
                table14DO.setUpdateTime(LocalDateTime.now());
                table14DO.setApplicationId(applicationId);
                userBaseTable14Mapper.insert(table14DO);
            } else {
                UserBaseTable14DO table14DO = userBaseTable14Mapper.selectById(vo.getTableId());
                table14DO.setApplicationId(applicationId);
                userBaseTable14Mapper.updateById(table14DO);
            }
        } else if (productType == 15) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable15DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable15DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable15DO::getCreateTime).last("LIMIT 1");
                UserBaseTable15DO table15DO = userBaseTable15Mapper.selectOne(queryWrapper);
                table15DO.setId(null);
                table15DO.setCreateTime(LocalDateTime.now());
                table15DO.setUpdateTime(LocalDateTime.now());
                table15DO.setApplicationId(applicationId);
                userBaseTable15Mapper.insert(table15DO);
            } else {
                UserBaseTable15DO table15DO = userBaseTable15Mapper.selectById(vo.getTableId());
                table15DO.setApplicationId(applicationId);
                userBaseTable15Mapper.updateById(table15DO);
            }
        } else if (productType == 16) {
            if (vo.getType().equals("1")) {
                //智能匹配，资料copy原有，新增新数据绑定，确保每个申请记录单独对应一份资料
                LambdaQueryWrapperX<UserBaseTable16DO> queryWrapper = new LambdaQueryWrapperX<>();
                queryWrapper.eq(UserBaseTable16DO::getUserId, vo.getUserId());
                queryWrapper.orderByDesc(UserBaseTable16DO::getCreateTime).last("LIMIT 1");
                UserBaseTable16DO table16DO = userBaseTable16Mapper.selectOne(queryWrapper);
                table16DO.setId(null);
                table16DO.setCreateTime(LocalDateTime.now());
                table16DO.setUpdateTime(LocalDateTime.now());
                table16DO.setApplicationId(applicationId);
                userBaseTable16Mapper.insert(table16DO);
            } else {
                UserBaseTable16DO table16DO = userBaseTable16Mapper.selectById(vo.getTableId());
                table16DO.setApplicationId(applicationId);
                userBaseTable16Mapper.updateById(table16DO);
            }
        }
    }

    @Override
    public int deleteUser(Long id) {
        return miniUserMapper.deleteById(new UserDO().setId(id));
    }

    @Override
    public int forbiddenUser(Long id) {
        UserDO userDO = new UserDO();
        userDO.setId(id);
        userDO.setStatus(1);
        return miniUserMapper.updateById(userDO);
    }

    @Override
    public MyTestResVo getMyOptionalTest(Long userId, Long productId) {
        MyTestResVo resVo = new MyTestResVo();
        List<ProductDO> product = new ArrayList<>();
        String amount = "0.0";

        //查找产品
//        LambdaQueryWrapper<ProductDO> hQueryWrapper = new Lambd222256aQueryWrapper<>();
//        hQueryWrapper.eq(ProductDO::getProductType, productId);
        List<ProductDO> productDOList = productMapper.selectList("id", productId);
        product.addAll(productDOList);

        ProductDO p = productDOList.get(0);

        //额度
        if (p.getProductType() == 1) {
            LambdaQueryWrapperX<UserBaseTable1DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable1DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable1DO::getCreateTime).last("LIMIT 1");
            // 限制结果为1条，即最新的一条
            List<UserBaseTable1DO> table1DOS = userBaseTable1Mapper.selectList(queryWrapper);
            if (table1DOS.size() > 0) {
                UserBaseTable1DO userBaseTable1DO = table1DOS.get(0);
                amount = CalculateUtils.calculateTable1(userBaseTable1DO, p);
            }
        } else if (p.getProductType() == 2) {
            LambdaQueryWrapperX<UserBaseTable2DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable2DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable2DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable2DO> table2DOS = userBaseTable2Mapper.selectList(queryWrapper);
            if (table2DOS.size() > 0) {
                UserBaseTable2DO table2DO = table2DOS.get(0);
                amount = CalculateUtils.calculateTable2(table2DO, p);
            }
        } else if (p.getProductType() == 3) {
            //暂无
            amount = CalculateUtils.calculateTable3();
        } else if (p.getProductType() == 4) {
            LambdaQueryWrapperX<UserBaseTable4DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable4DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable4DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable4DO> table4DOS = userBaseTable4Mapper.selectList(queryWrapper);
            if (table4DOS.size() > 0) {
                UserBaseTable4DO table4DO = table4DOS.get(0);
                amount = CalculateUtils.calculateTable4(table4DO, p);
            }
        } else if (p.getProductType() == 5) {
            LambdaQueryWrapperX<UserBaseTable5DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable5DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable5DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable5DO> table5DOS = userBaseTable5Mapper.selectList(queryWrapper);
            if (table5DOS.size() > 0) {
                UserBaseTable5DO table5DO = table5DOS.get(0);
                amount = CalculateUtils.calculateTable5(table5DO, p);
            }
        } else if (p.getProductType() == 6) {
            LambdaQueryWrapperX<UserBaseTable6DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable6DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable6DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable6DO> table6DOS = userBaseTable6Mapper.selectList(queryWrapper);
            if (table6DOS.size() > 0) {
                UserBaseTable6DO table6DO = table6DOS.get(0);
                amount = CalculateUtils.calculateTable6(table6DO);
            }
        } else if (p.getProductType() == 7) {
            LambdaQueryWrapperX<UserBaseTable7DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable7DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable7DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable7DO> table7DOS = userBaseTable7Mapper.selectList(queryWrapper);
            if (table7DOS.size() > 0) {
                UserBaseTable7DO table7DO = table7DOS.get(0);
                amount = CalculateUtils.calculateTable7(table7DO, p);
            }
        } else if (p.getProductType() == 8) {
            LambdaQueryWrapperX<UserBaseTable8DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable8DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable8DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable8DO> table8DOS = userBaseTable8Mapper.selectList(queryWrapper);
            if (table8DOS.size() > 0) {
                UserBaseTable8DO table8DO = table8DOS.get(0);
                amount = CalculateUtils.calculateTable8(table8DO, p);
            }
        } else if (p.getProductType() == 9) {
            LambdaQueryWrapperX<UserBaseTable9DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable9DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable9DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable9DO> table9DOS = userBaseTable9Mapper.selectList(queryWrapper);
            if (table9DOS.size() > 0) {
                UserBaseTable9DO table9DO = table9DOS.get(0);
                amount = CalculateUtils.calculateTable9(table9DO, p);
            }
        } else if (p.getProductType() == 10) {
            LambdaQueryWrapperX<UserBaseTable10DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable10DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable10DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable10DO> table10DOS = userBaseTable10Mapper.selectList(queryWrapper);
            if (table10DOS.size() > 0) {
                UserBaseTable10DO table10DO = table10DOS.get(0);
                amount = CalculateUtils.calculateTable10(table10DO, p);
            }
        } else if (p.getProductType() == 11) {
            LambdaQueryWrapperX<UserBaseTable11DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable11DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable11DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable11DO> table11DOS = userBaseTable11Mapper.selectList(queryWrapper);
            if (table11DOS.size() > 0) {
                UserBaseTable11DO table11DO = table11DOS.get(0);
                amount = CalculateUtils.calculateTable11(table11DO, p);
            }
        } else if (p.getProductType() == 12) {
            LambdaQueryWrapperX<UserBaseTable12DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable12DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable12DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable12DO> table12DOS = userBaseTable12Mapper.selectList(queryWrapper);
            if (table12DOS.size() > 0) {
                UserBaseTable12DO table12DO = table12DOS.get(0);
                amount = CalculateUtils.calculateTable12(table12DO, p);
            }
        } else if (p.getProductType() == 13) {
            LambdaQueryWrapperX<UserBaseTable13DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable13DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable13DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable13DO> table13DOS = userBaseTable13Mapper.selectList(queryWrapper);
            if (table13DOS.size() > 0) {
                UserBaseTable13DO table13DO = table13DOS.get(0);
                amount = CalculateUtils.calculateTable13(table13DO, p);
            }
        } else if (p.getProductType() == 14) {
            LambdaQueryWrapperX<UserBaseTable14DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable14DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable14DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable14DO> table14DOS = userBaseTable14Mapper.selectList(queryWrapper);
            if (table14DOS.size() > 0) {
                UserBaseTable14DO table14DO = table14DOS.get(0);
                amount = CalculateUtils.calculateTable14(table14DO, p);
            }
        } else if (p.getProductType() == 15) {
            LambdaQueryWrapperX<UserBaseTable15DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable15DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable15DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable15DO> table15DOS = userBaseTable15Mapper.selectList(queryWrapper);
            if (table15DOS.size() > 0) {
                UserBaseTable15DO table15DO = table15DOS.get(0);
                amount = CalculateUtils.calculateTable15(table15DO, p);
            }
        } else if (p.getProductType() == 16) {
            LambdaQueryWrapperX<UserBaseTable16DO> queryWrapper = new LambdaQueryWrapperX<>();
            queryWrapper.eq(UserBaseTable16DO::getUserId, userId);
            queryWrapper.orderByDesc(UserBaseTable16DO::getCreateTime).last("LIMIT 1");
            List<UserBaseTable16DO> table16DOS = userBaseTable16Mapper.selectList(queryWrapper);
            if (table16DOS.size() > 0) {
                UserBaseTable16DO table16DO = table16DOS.get(0);
                amount = CalculateUtils.calculateTable16(table16DO, p);
            }
        }
        p.setYgMaxAmount(amount);
        resVo.setAmount(amount);
        resVo.setProductList(ProductConvert.INSTANCE.convertList(product));
        return resVo;
    }

    @Override
    @Transactional
    public CommonResult<String> transferWarrant(TransferWarrantReqVo reqsVo) {
        CommonResult<String> result = new CommonResult<>();

        ApplicationRecordDO app = applicationRecordMapper.selectById(reqsVo.getOrderId());
        Integer flow = Integer.valueOf(app.getFlowN());
        if (flow >= 5) {
            result.setCode(0);
            result.setMsg("操作成功");
            result.setData("已转权证，请勿重复操作");
        } else {
            if (reqsVo.getVoList() == null || reqsVo.getVoList().size() <= 0) {
                result.setCode(500);
                result.setMsg("操作失败，请选择推荐产品后再转权证处理！");
                result.setData("操作失败，请选择推荐产品后再转权证处理！");
            } else {
                result.setCode(0);
                result.setMsg("操作成功");
                result.setData("订单已转权证处理");

                //更改订单状态
                ApplicationRecordDO applicationRecordDO = new ApplicationRecordDO();
                applicationRecordDO.setId(reqsVo.getOrderId());
                applicationRecordDO.setFlowN("5");
                applicationRecordDO.setApplyState("1");
                applicationRecordMapper.updateById(applicationRecordDO);

                if (app.getWarrantId() == null) {
                    result.setCode(0);
                    result.setMsg("操作成功");
                    result.setData("订单已转权证处理，当前申请人未分配权证员，请联系管理设置");
                }
                //删除当前流程审核记录，重新生成审核记录
                processRecordMapper.deleteProcessRecordById(reqsVo.getOrderId());

                //先删除当前产品准入内容
                productAccessRecordMapper.deleteRecordById(reqsVo.getOrderId());

                //用户申请记录
                ProcessRecordDO processRecordDO = new ProcessRecordDO();
                processRecordDO.setUserId(app.getUserId());
                processRecordDO.setFlowN("5");
                processRecordDO.setIsFail("0");
                processRecordDO.setApplicationId(reqsVo.getOrderId());
                processRecordMapper.insert(processRecordDO);

                //新增产品备注
                List<ProductAccessRecordDO> recordList = new ArrayList<>();
                for (ProductAccessRecordCreateReqVO vo : reqsVo.getVoList()) {
                    ProductAccessDO accessDO = productAccessMapper.selectById(vo.getId());
                    if (accessDO != null) {
                        ProductAccessRecordDO recordDO = ProductAccessRecordConvert.INSTANCE.convertAccess(accessDO);
                        recordDO.setMonthlyInfo(vo.getMonthlyInfo());
                        recordDO.setQuotaFormula(vo.getQuotaFormula());
                        recordDO.setUserId(app.getUserId());
                        recordDO.setOrderNo(reqsVo.getOrderId());
                        recordDO.setAccessId(vo.getId());
                        recordDO.setId(null);
                        productAccessRecordMapper.insert(recordDO);

                        //查询准入产品提成参数
                        ProductAccessPercentageDO productAccess = percentageService.getProductAccessPercentageByAccessId(recordDO.getAccessId());
                        if (productAccess != null) {
                            //保存每个准入产品提出参数
                            ApplicationDeductRecordDO deductRecord = new ApplicationDeductRecordDO();
                            BeanUtils.copyProperties(productAccess, deductRecord);
                            deductRecord.setOrderId(reqsVo.getOrderId());
                            deductRecord.setProductAccessRecordId(recordDO.getId());
                            deductRecord.setId(null);
                            deductRecord.setCreateTime(LocalDateTime.now());
                            deductRecord.setUpdateTime(LocalDateTime.now());
                            deductRecordMapper.insert(deductRecord);
                            //结单时还需要计算，暂时不计算
                            //CalculateUtils.getDeduct(percentageDO,recordDO.getQuotaFormula());
                        }
                    } else {
                        throw exception(PRODUCT_ACCESS_NOT_EXISTS);
                    }
                }
                //productAccessRecordMapper.insertBatch(recordList);

                //发送消息通知
                notificationService.sendOrderNotification("订单已转权证处理！", "test007", app.getUserId());

            }
        }

        return result;
    }

    @Override
    public SalesmanInfosResVo getSalesmanInfos(Long userId) {
        SalesmanInfosResVo resVo = new SalesmanInfosResVo();
        UserDO userDO = miniUserMapper.selectById(userId);
        BeanUtils.copyProperties(userDO, resVo);
        //推荐产品
        List<ProductDO> productDOList = productMapper.selectListTopFive();
        if (productDOList.size() > 0) {
            resVo.setProductRespList(ProductConvert.INSTANCE.convertList(productDOList));
        }
        return resVo;
    }

    @Override
    public List<PropertyResVo> getMyProperty(Long userId) throws Exception {
        List<PropertyResVo> resVoList = new ArrayList<>();

        //查询16个表
        List<UserBaseTable1DO> u1 = userBaseTable1Mapper.selectList("user_id", userId);
        List<UserBaseTable2DO> u2 = userBaseTable2Mapper.selectList("user_id", userId);
        List<UserBaseTable3DO> u3 = userBaseTable3Mapper.selectList("user_id", userId);
        List<UserBaseTable4DO> u4 = userBaseTable4Mapper.selectList("user_id", userId);
        List<UserBaseTable5DO> u5 = userBaseTable5Mapper.selectList("user_id", userId);
        List<UserBaseTable6DO> u6 = userBaseTable6Mapper.selectList("user_id", userId);
        List<UserBaseTable7DO> u7 = userBaseTable7Mapper.selectList("user_id", userId);
        List<UserBaseTable8DO> u8 = userBaseTable8Mapper.selectList("user_id", userId);
        List<UserBaseTable9DO> u9 = userBaseTable9Mapper.selectList("user_id", userId);
        List<UserBaseTable10DO> u10 = userBaseTable10Mapper.selectList("user_id", userId);
        List<UserBaseTable11DO> u11 = userBaseTable11Mapper.selectList("user_id", userId);
        List<UserBaseTable12DO> u12 = userBaseTable12Mapper.selectList("user_id", userId);
        List<UserBaseTable13DO> u13 = userBaseTable13Mapper.selectList("user_id", userId);
        List<UserBaseTable14DO> u14 = userBaseTable14Mapper.selectList("user_id", userId);
        List<UserBaseTable15DO> u15 = userBaseTable15Mapper.selectList("user_id", userId);
        List<UserBaseTable16DO> u16 = userBaseTable16Mapper.selectList("user_id", userId);


        PropertyResVo r1 = new PropertyResVo();
        r1.setTypeName("按揭房信贷");
        if (u1.size() > 0) {
            int count = 100;
            UserBaseTable1DO u1DO = u1.get(0);
            List<String> list = isObjectFieldEmpty(u1DO);
            int number = list.size() * 10;
            count = count - number;
            r1.setPercentum(count);
        } else {
            r1.setPercentum(0);
        }

        PropertyResVo r2 = new PropertyResVo();
        r2.setTypeName("保单贷");
        if (u2.size() > 0) {
            int count = 100;
            UserBaseTable2DO u2DO = u2.get(0);
            List<String> list = isObjectFieldEmpty(u2DO);
            int number = list.size() * 10;
            count = count - number;
            r2.setPercentum(count);
        } else {
            r2.setPercentum(0);
        }

        PropertyResVo r3 = new PropertyResVo();
        r3.setTypeName("个人贴息贷");
        if (u3.size() > 0) {
            int count = 100;
            UserBaseTable3DO u3DO = u3.get(0);
            List<String> list = isObjectFieldEmpty(u3DO);
            int number = list.size() * 10;
            count = count - number;
            r3.setPercentum(count);
        } else {
            r3.setPercentum(0);
        }

        PropertyResVo r4 = new PropertyResVo();
        r4.setTypeName("工薪贷");
        if (u4.size() > 0) {
            int count = 100;
            UserBaseTable4DO u4DO = u4.get(0);
            List<String> list = isObjectFieldEmpty(u4DO);
            int number = list.size() * 10;
            count = count - number;
            r4.setPercentum(count);
        } else {
            r4.setPercentum(0);
        }

        PropertyResVo r5 = new PropertyResVo();
        r5.setTypeName("公积金贷");
        if (u5.size() > 0) {
            int count = 100;
            UserBaseTable5DO u5DO = u5.get(0);
            List<String> list = isObjectFieldEmpty(u5DO);
            int number = list.size() * 10;
            count = count - number;
            r5.setPercentum(count);
        } else {
            r5.setPercentum(0);
        }

        PropertyResVo r6 = new PropertyResVo();
        r6.setTypeName("企业贴息贷款");
        if (u6.size() > 0) {
            int count = 100;
            UserBaseTable6DO u6DO = u6.get(0);
            List<String> list = isObjectFieldEmpty(u6DO);
            int number = list.size() * 10;
            count = count - number;
            r6.setPercentum(count);
        } else {
            r6.setPercentum(0);
        }


        PropertyResVo r7 = new PropertyResVo();
        r7.setTypeName("全款车按揭车信贷");
        if (u7.size() > 0) {
            int count = 100;
            UserBaseTable7DO u7DO = u7.get(0);
            List<String> list = isObjectFieldEmpty(u7DO);
            int number = list.size() * 10;
            count = count - number;
            r7.setPercentum(count);
        } else {
            r7.setPercentum(0);
        }

        PropertyResVo r8 = new PropertyResVo();
        r8.setTypeName("商业商住楼写字楼厂房一抵押");
        if (u8.size() > 0) {
            int count = 100;
            UserBaseTable8DO u8DO = u8.get(0);
            List<String> list = isObjectFieldEmpty(u8DO);
            int number = list.size() * 10;
            count = count - number;
            r8.setPercentum(count);
        } else {
            r8.setPercentum(0);
        }

        PropertyResVo r9 = new PropertyResVo();
        r9.setTypeName("商业商住楼写字楼二次抵押");
        if (u9.size() > 0) {
            int count = 100;
            UserBaseTable9DO u9DO = u9.get(0);
            List<String> list = isObjectFieldEmpty(u9DO);
            int number = list.size() * 10;
            count = count - number;
            r9.setPercentum(count);
        } else {
            r9.setPercentum(0);
        }

        PropertyResVo r10 = new PropertyResVo();
        r10.setTypeName("商业写字楼按揭贷款");
        if (u10.size() > 0) {
            int count = 100;
            UserBaseTable10DO u10DO = u10.get(0);
            List<String> list = isObjectFieldEmpty(u10DO);
            int number = list.size() * 10;
            count = count - number;
            r10.setPercentum(count);
        } else {
            r10.setPercentum(0);
        }

        PropertyResVo r11 = new PropertyResVo();
        r11.setTypeName("税贷");
        if (u11.size() > 0) {
            int count = 100;
            UserBaseTable11DO u11DO = u11.get(0);
            List<String> list = isObjectFieldEmpty(u11DO);
            int number = list.size() * 10;
            count = count - number;
            r11.setPercentum(count);
        } else {
            r11.setPercentum(0);
        }

        PropertyResVo r12 = new PropertyResVo();
        r12.setTypeName("小微企业贷");
        if (u12.size() > 0) {
            int count = 100;
            UserBaseTable12DO u12DO = u12.get(0);
            List<String> list = isObjectFieldEmpty(u12DO);
            int number = list.size() * 10;
            count = count - number;
            r12.setPercentum(count);
        } else {
            r12.setPercentum(0);
        }

        PropertyResVo r13 = new PropertyResVo();
        r13.setTypeName("企业发票贷");
        if (u13.size() > 0) {
            int count = 100;
            UserBaseTable13DO u13DO = u13.get(0);
            List<String> list = isObjectFieldEmpty(u13DO);
            int number = list.size() * 10;
            count = count - number;
            r13.setPercentum(count);
        } else {
            r13.setPercentum(0);
        }

        PropertyResVo r14 = new PropertyResVo();
        r14.setTypeName("住宅按揭贷");
        if (u14.size() > 0) {
            int count = 100;
            UserBaseTable14DO u14DO = u14.get(0);
            List<String> list = isObjectFieldEmpty(u14DO);
            int number = list.size() * 10;
            count = count - number;
            r14.setPercentum(count);
        } else {
            r14.setPercentum(0);
        }

        PropertyResVo r15 = new PropertyResVo();
        r15.setTypeName("住宅抵押");
        if (u15.size() > 0) {
            int count = 100;
            UserBaseTable15DO u15DO = u15.get(0);
            List<String> list = isObjectFieldEmpty(u15DO);
            int number = list.size() * 10;
            count = count - number;
            r15.setPercentum(count);
        } else {
            r15.setPercentum(0);
        }

        PropertyResVo r16 = new PropertyResVo();
        r16.setTypeName("住宅二次抵押");
        if (u16.size() > 0) {
            int count = 100;
            UserBaseTable16DO u16DO = u16.get(0);
            List<String> list = isObjectFieldEmpty(u16DO);
            int number = list.size() * 10;
            count = count - number;
            r16.setPercentum(count);
        } else {
            r16.setPercentum(0);
        }

        resVoList.add(r1);
        resVoList.add(r2);
        resVoList.add(r3);
        resVoList.add(r4);
        resVoList.add(r5);
        resVoList.add(r6);
        resVoList.add(r7);
        resVoList.add(r8);
        resVoList.add(r9);
        resVoList.add(r10);
        resVoList.add(r11);
        resVoList.add(r12);
        resVoList.add(r13);
        resVoList.add(r14);
        resVoList.add(r15);
        resVoList.add(r16);

        return resVoList;
    }

    @Override
    public CommonResult<String> getCheckProductInfo(Long userId, String productTypeId) {
        CommonResult<String> commonResult = new CommonResult<>();
        commonResult.setCode(0);
        //查询16个表
        String str = "";
        if (productTypeId.equals("1")) {
            List<UserBaseTable1DO> u1 = userBaseTable1Mapper.selectList("user_id", userId);
            if (u1.size() <= 0) {
                commonResult.setData("1");
                commonResult.setMsg("请填写按揭房信贷资料");
            }
        } else if (productTypeId.equals("2")) {
            List<UserBaseTable2DO> u2 = userBaseTable2Mapper.selectList("user_id", userId);
            if (u2.size() <= 0) {
                commonResult.setData("2");
                commonResult.setMsg("请填写保单贷资料");
            }
        } else if (productTypeId.equals("3")) {
            List<UserBaseTable3DO> u3 = userBaseTable3Mapper.selectList("user_id", userId);
            if (u3.size() <= 0) {
                commonResult.setData("3");
                commonResult.setMsg("请填写个人贴息贷资料");
            }
        } else if (productTypeId.equals("4")) {
            List<UserBaseTable4DO> u4 = userBaseTable4Mapper.selectList("user_id", userId);
            if (u4.size() <= 0) {
                commonResult.setData("4");
                commonResult.setMsg("请填写工薪贷资料");
            }
        } else if (productTypeId.equals("5")) {
            List<UserBaseTable5DO> u5 = userBaseTable5Mapper.selectList("user_id", userId);
            if (u5.size() <= 0) {
                commonResult.setData("5");
                commonResult.setMsg("请填写公积金贷资料");
            }
        } else if (productTypeId.equals("6")) {
            List<UserBaseTable6DO> u6 = userBaseTable6Mapper.selectList("user_id", userId);
            if (u6.size() <= 0) {
                commonResult.setData("6");
                commonResult.setMsg("请填写企业贴息贷资料");
            }
        } else if (productTypeId.equals("7")) {
            List<UserBaseTable7DO> u7 = userBaseTable7Mapper.selectList("user_id", userId);
            if (u7.size() <= 0) {
                commonResult.setData("7");
                commonResult.setMsg("请填写全款车按揭车信贷资料");
            }
        } else if (productTypeId.equals("8")) {
            List<UserBaseTable8DO> u8 = userBaseTable8Mapper.selectList("user_id", userId);
            if (u8.size() <= 0) {
                commonResult.setData("8");
                commonResult.setMsg("请填写商业商住楼写字楼厂房一抵押资料");
            }
        } else if (productTypeId.equals("9")) {
            List<UserBaseTable9DO> u9 = userBaseTable9Mapper.selectList("user_id", userId);
            if (u9.size() <= 0) {
                commonResult.setData("9");
                commonResult.setMsg("请填写商业商住楼写字楼二次抵押资料");
            }
        } else if (productTypeId.equals("10")) {
            List<UserBaseTable10DO> u10 = userBaseTable10Mapper.selectList("user_id", userId);
            if (u10.size() <= 0) {
                commonResult.setData("10");
                commonResult.setMsg("请填写商业写字楼按揭贷款资料");
            }
        } else if (productTypeId.equals("11")) {
            List<UserBaseTable11DO> u11 = userBaseTable11Mapper.selectList("user_id", userId);
            if (u11.size() <= 0) {
                commonResult.setData("11");
                commonResult.setMsg("请填写税贷资料");
            }
        } else if (productTypeId.equals("12")) {
            List<UserBaseTable12DO> u12 = userBaseTable12Mapper.selectList("user_id", userId);
            if (u12.size() <= 0) {
                commonResult.setData("12");
                commonResult.setMsg("请填写企业流水贷资料");
            }
        } else if (productTypeId.equals("13")) {
            List<UserBaseTable13DO> u13 = userBaseTable13Mapper.selectList("user_id", userId);
            if (u13.size() <= 0) {
                commonResult.setData("13");
                commonResult.setMsg("请填写企业发票贷资料");
            }
        } else if (productTypeId.equals("14")) {
            List<UserBaseTable14DO> u14 = userBaseTable14Mapper.selectList("user_id", userId);
            if (u14.size() <= 0) {
                commonResult.setData("14");
                commonResult.setMsg("请填写住宅按揭贷款资料");
            }
        } else if (productTypeId.equals("15")) {
            List<UserBaseTable15DO> u15 = userBaseTable15Mapper.selectList("user_id", userId);
            if (u15.size() <= 0) {
                commonResult.setData("15");
                commonResult.setMsg("请填写完成住宅抵押资料");
            }
        } else if (productTypeId.equals("16")) {
            List<UserBaseTable16DO> u16 = userBaseTable16Mapper.selectList("user_id", userId);
            if (u16.size() <= 0) {
                commonResult.setData("16");
                commonResult.setMsg("请填写完成住宅二次抵押资料");
            }
        }
        return commonResult;
    }


    /**
     * @description 用户提交资料-业务审核填写资料后-匹配产品准入的产品
     */
    @Override
    public List<ProductAccessDO> getCheckProductAccess(String orderId) {
        List<ProductAccessDO> recordDOS = new ArrayList<>();

        Integer userType = getLoginUser().getUserType();

        //recordDOS = productAccessMapper.selectList();

        ////获取用户申请记录
        ApplicationRecordDO app = applicationRecordMapper.selectById(orderId);
//        ////查询产品对应的公示表
//        ProductDO productDO = productMapper.selectById(app.getProductId());
//        PublicityTypeDO typeDO = publicityTypeMapper.selectById(productDO.getProductType());
//        //公示表
//        String tableName = typeDO.getAliasName();
        //获取当前订单，业务员填写的表单资料和产品准入的产品准入项对比
        LambdaQueryWrapper<UserTablesAuditDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserTablesAuditDO::getOrderId, orderId);
        List<UserTablesAuditDO> list = userTablesAuditMapper.selectList(wrapper);
        Map<String, List<UserTablesAuditDO>> listMap = DataConversionUtils.groupByStream(list);
        for (Map.Entry<String, List<UserTablesAuditDO>> entry : listMap.entrySet()) {
            String key = entry.getKey();
            List<UserTablesAuditDO> lists = entry.getValue();
            //匹配准入项
            LambdaQueryWrapper<ProductAccessItemDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductAccessItemDO::getTypeNames, key);
            queryWrapper.groupBy(ProductAccessItemDO::getProductAccessId);
            List<ProductAccessItemDO> itemDOS = productAccessItemMapper.selectList(queryWrapper);
            if (itemDOS.size() > 0) {

                //产品准入-产品
                for (ProductAccessItemDO itemDO : itemDOS) {
                    ProductAccessDO accessDO = productAccessMapper.selectById(itemDO.getProductAccessId());
                    String bank = accessDO.getBank();
                    List<ProductAccessItemDO> itemList = productAccessItemMapper.selectList(
                            new LambdaQueryWrapper<ProductAccessItemDO>()
                                    .eq(ProductAccessItemDO::getProductAccessId, itemDO.getProductAccessId())
                                    .eq(ProductAccessItemDO::getTypeNames, itemDO.getTypeNames()));
                    boolean flag = CalculateUtils.getProductCheck(itemList, lists, bank, accessDO.getProductName());
                    if (flag) {
                        //把符合的产品放入list
                        ProductAccessDO productAccessDO = productAccessMapper.selectById(itemDO.getProductAccessId());
                        productAccessDO.setTypeNames(key);
                        recordDOS.add(productAccessDO);
                    }
                }
            }
        }

        List<ProductAccessDO> doList = new ArrayList<>();
        //计算月供、额度等
        if (recordDOS.size() > 0) {
            String amount = app.getAmount();
            for (ProductAccessDO accessDO : recordDOS) {
                //查询提成参数
                ProductAccessPercentageDO percentageDO = percentageService.getProductAccessPercentageByAccessId(accessDO.getId());
                ArrayList<BigDecimal> m = new ArrayList<>();
                String[] str = amount.split("—");
                PublicityTypeDO typeDO = publicityTypeMapper.selectById(accessDO.getPublicityTypeId());

                //年龄
                LambdaQueryWrapper<UserTablesAuditDO> tables = new LambdaQueryWrapper<>();
                tables.eq(UserTablesAuditDO::getOrderId, orderId);
                tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                tables.eq(UserTablesAuditDO::getCategoryName, "年龄");
                UserTablesAuditDO auditDo = userTablesAuditMapper.selectOne(tables);
                int age = 0;
                if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                    age = Integer.valueOf(auditDo.getResultValue());
                }
                if (accessDO.getPublicityTypeId() == 1) {//按揭房信贷
                    //建筑面积*X=1个额度
                    LambdaQueryWrapperX<UserBaseTable1DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable1DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable1DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable1DO> table1DOS = userBaseTable1Mapper.selectList(queryWrapper);
                    if (table1DOS.size() > 0) {
                        UserBaseTable1DO table1DO = table1DOS.get(0);
                        BigDecimal areaOfStructure = table1DO.getAreaOfStructure();
                        BigDecimal ed = areaOfStructure.multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                        //先息后本=预估额度×年化利率÷还款周期=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), 0);
                    }
                } else if (accessDO.getPublicityTypeId() == 2) { //保单贷
                    //年缴费合计*X倍-整体负债合计=1个额度
                    LambdaQueryWrapperX<UserBaseTable2DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable2DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable2DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable2DO> table2DOS = userBaseTable2Mapper.selectList(queryWrapper);
                    if (table2DOS.size() > 0) {
                        UserBaseTable2DO table2DO = table2DOS.get(0);
                        BigDecimal yearAmount = table2DO.getAnnualPayment();
                        //整体负债合计
                        tables = new LambdaQueryWrapper<>();
                        tables.eq(UserTablesAuditDO::getOrderId, orderId);
                        tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                        tables.eq(UserTablesAuditDO::getCategoryName, "整体负债合计");
                        auditDo = userTablesAuditMapper.selectOne(tables);
                        BigDecimal ztfz = new BigDecimal(BigInteger.ZERO);
                        if (auditDo != null) {
                            if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                                ztfz = new BigDecimal(auditDo.getResultValue());
                            }
                        }

                        //年缴费合计*X倍-整体负债合计=1个额度
                        BigDecimal ed = yearAmount.multiply(accessDO.getMultiple()).subtract(ztfz).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                        //先息后本=预估额度×年化利率÷还款周期=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), 0);
                    }
                } else if (accessDO.getPublicityTypeId() == 4) { //工薪贷
                    //年薪×Z倍—负债=额度
                    LambdaQueryWrapperX<UserBaseTable4DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable4DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable4DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable4DO> table4DOS = userBaseTable4Mapper.selectList(queryWrapper);
                    if (table4DOS.size() > 0) {
                        UserBaseTable4DO table4DO = table4DOS.get(0);
                        BigDecimal yearAmount = table4DO.getAnnualSalary();
                        //整体负债合计
                        tables = new LambdaQueryWrapper<>();
                        tables.eq(UserTablesAuditDO::getOrderId, orderId);
                        tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                        tables.eq(UserTablesAuditDO::getCategoryName, "整体负债合计");
                        auditDo = userTablesAuditMapper.selectOne(tables);
                        BigDecimal ztfz = new BigDecimal(BigInteger.ZERO);
                        if (auditDo != null) {
                            if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                                ztfz = new BigDecimal(auditDo.getResultValue());
                            }
                        }
                        //年缴费合计*Z倍-整体负债合计=1个额度
                        BigDecimal ed = yearAmount.multiply(accessDO.getMultiple()).subtract(ztfz).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                        //先息后本=预估额度×年化利率÷还款周期=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), 0);
                    }
                } else if (accessDO.getPublicityTypeId() == 5) {
                    LambdaQueryWrapperX<UserBaseTable5DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable5DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable5DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable5DO> table5DOS = userBaseTable5Mapper.selectList(queryWrapper);
                    if (table5DOS.size() > 0) {
                        UserBaseTable5DO table5DO = table5DOS.get(0);
                        BigDecimal yearMoney = table5DO.getPolicyYearPayment();
                        //年缴费合计*X成=1个额度
                        BigDecimal ed = yearMoney.multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                        //先息后本=预估额度×年化利率÷还款周期=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                    }
                } else if (accessDO.getPublicityTypeId() == 7) { //车辆信贷
                    //车辆评估价*X成—按揭车剩余本金=1个额度
                    //车辆评估价
                    BigDecimal pgj = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "车辆评估价");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            pgj = new BigDecimal(convertWanToYuan(auditDo.getResultValue()));
                        }
                    }

                    //按揭车剩余本金
                    BigDecimal bj = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "按揭车剩余本金");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            bj = new BigDecimal(convertWanToYuan(auditDo.getResultValue()));
                        }
                    }

                    BigDecimal ed = pgj.multiply(accessDO.getPortions()).subtract(bj).setScale(2, RoundingMode.HALF_UP);
                    ed = checkAmount(ed, accessDO.getMaxAmount());
                    ed = CalculateUtils.formatZeroMoney(ed);
                    accessDO.setQuotaFormula(ed);

                    //等额本金，等额本息=（预估额度÷还款周期）+（预估额度×年化利率÷12）=月供
                    //先息后本=预估额度×年化利率÷还款周期=月供
                    m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                } else if (accessDO.getPublicityTypeId() == 8) {//商业一抵押
                    LambdaQueryWrapperX<UserBaseTable8DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable8DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable8DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable8DO> table8DOS = userBaseTable8Mapper.selectList(queryWrapper);
                    if (table8DOS.size() > 0) {
                        UserBaseTable8DO table8DO = table8DOS.get(0);
                        BigDecimal zjdj = table8DO.getRent();
                        BigDecimal mj = new BigDecimal(table8DO.getAreaOfStructure());
                        //租金单价*建筑面积*X倍*Y成=预估额度
                        BigDecimal ed = zjdj.multiply(mj).multiply(accessDO.getMultiple()).multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //额度/（80-客户年龄）+（额度*年华利率/12）=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                    }
                } else if (accessDO.getPublicityTypeId() == 9) {//商业二抵押
                    LambdaQueryWrapperX<UserBaseTable9DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable9DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable9DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable9DO> table9DOS = userBaseTable9Mapper.selectList(queryWrapper);
                    if (table9DOS.size() > 0) {
                        UserBaseTable9DO table9DO = table9DOS.get(0);
                        BigDecimal zjdj = table9DO.getRent();
                        BigDecimal mj = new BigDecimal(table9DO.getAreaOfStructure());
                        //租金单价*建筑面积*X倍*Y成=预估额度
                        BigDecimal ed = zjdj.multiply(mj).multiply(accessDO.getMultiple()).multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //额度/（80-客户年龄）+（额度*年华利率/12）=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                    }
                } else if (accessDO.getPublicityTypeId() == 10) { //商业按揭
                    LambdaQueryWrapperX<UserBaseTable10DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable10DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable10DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable10DO> table10DOS = userBaseTable10Mapper.selectList(queryWrapper);
                    if (table10DOS.size() > 0) {
                        UserBaseTable10DO table10DO = table10DOS.get(0);
                        BigDecimal zjdj = table10DO.getRent();
                        BigDecimal mj = new BigDecimal(table10DO.getAreaOfStructure());
                        //租金单价*建筑面积*X倍*Y成=预估额度
                        BigDecimal ed = zjdj.multiply(mj).multiply(accessDO.getMultiple()).multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //额度/（80-客户年龄）+（额度*年华利率/12）=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                    }
                } else if (accessDO.getPublicityTypeId() == 11) { //企业税贷
                    //近一年纳税总金额*X倍—43条整体负债=1个额度

                    BigDecimal countMoney = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "企业交税金额（近一年）");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            countMoney = new BigDecimal(auditDo.getResultValue());
                        }
                    }

                    BigDecimal liabilities = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "整体负债合计");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            liabilities = new BigDecimal(auditDo.getResultValue());
                        }
                    }


                    BigDecimal ed = countMoney.multiply(accessDO.getMultiple()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
                    ed = checkAmount(ed, accessDO.getMaxAmount());
                    ed = CalculateUtils.formatZeroMoney(ed);
                    accessDO.setQuotaFormula(ed);
                    //额度*年华利率/12=月供
                    m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);

                } else if (accessDO.getPublicityTypeId() == 12) { //企业流水贷
                    //年经营流水*X—43条整体负债=1个额度

                    BigDecimal countMoney = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.like(UserTablesAuditDO::getCategoryName, "年经营流水合计：对公流水+银联收入+个人流水");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            countMoney = new BigDecimal(auditDo.getResultValue());
                        }
                    }

                    BigDecimal liabilities = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "整体负债合计");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            liabilities = new BigDecimal(auditDo.getResultValue());
                        }
                    }


                    BigDecimal ed = countMoney.multiply(accessDO.getMultiple()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
                    ed = checkAmount(ed, accessDO.getMaxAmount());
                    ed = CalculateUtils.formatZeroMoney(ed);
                    accessDO.setQuotaFormula(ed);
                    //额度*年华利率/12=月供
                    m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                } else if (accessDO.getPublicityTypeId() == 13) { //企业发票贷
                    //企业年开票金额*X—43条整体负债=额度

                    BigDecimal countMoney = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.like(UserTablesAuditDO::getCategoryName, "企业年开票金额");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            countMoney = new BigDecimal(auditDo.getResultValue());
                        }
                    }

                    BigDecimal liabilities = new BigDecimal(BigInteger.ZERO);
                    tables = new LambdaQueryWrapper<>();
                    tables.eq(UserTablesAuditDO::getOrderId, orderId);
                    tables.eq(UserTablesAuditDO::getTypeName, typeDO.getAliasName());
                    tables.eq(UserTablesAuditDO::getCategoryName, "整体负债合计");
                    auditDo = userTablesAuditMapper.selectOne(tables);
                    if (auditDo != null) {
                        if (StringUtils.isNotEmpty(auditDo.getResultValue())) {
                            liabilities = new BigDecimal(auditDo.getResultValue());
                        }
                    }

                    BigDecimal ed = countMoney.multiply(accessDO.getMultiple()).subtract(liabilities).setScale(2, RoundingMode.HALF_UP);
                    ed = checkAmount(ed, accessDO.getMaxAmount());
                    ed = CalculateUtils.formatZeroMoney(ed);
                    accessDO.setQuotaFormula(ed);
                    //额度*年华利率/12=月供
                    m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);

                } else if (accessDO.getPublicityTypeId() == 14) { //住宅按揭
                    LambdaQueryWrapperX<UserBaseTable14DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable14DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable14DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable14DO> table14DOS = userBaseTable14Mapper.selectList(queryWrapper);
                    if (table14DOS.size() > 0) {
                        UserBaseTable14DO table14DO = table14DOS.get(0);
                        BigDecimal pgj = table14DO.getValuationPrice();
                        BigDecimal mj = new BigDecimal(table14DO.getAreaOfStructure());
                        //评估价*建筑面积*X成=额度
                        BigDecimal ed = pgj.multiply(mj).multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        //额度/（70-客户年龄）+（额度*年华利率/12）=月供
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), age);
                    }
                } else if (accessDO.getPublicityTypeId() == 15) { //住宅抵押
                    LambdaQueryWrapperX<UserBaseTable15DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable15DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable15DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable15DO> table15DOS = userBaseTable15Mapper.selectList(queryWrapper);
                    if (table15DOS.size() > 0) {
                        UserBaseTable15DO table15DO = table15DOS.get(0);
                        BigDecimal pgj = table15DO.getValuationPrice();
                        BigDecimal mj = new BigDecimal(table15DO.getAreaOfStructure());
                        //评估价*建筑面积*X成=额度
                        BigDecimal ed = pgj.multiply(mj).multiply(accessDO.getPortions()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), 0);
                    }
                } else if (accessDO.getPublicityTypeId() == 16) { // 住宅二次抵押
                    LambdaQueryWrapperX<UserBaseTable16DO> queryWrapper = new LambdaQueryWrapperX<>();
                    queryWrapper.eq(UserBaseTable16DO::getApplicationId, app.getId());
                    queryWrapper.orderByDesc(UserBaseTable16DO::getCreateTime).last("LIMIT 1");
                    List<UserBaseTable16DO> table16DOS = userBaseTable16Mapper.selectList(queryWrapper);
                    if (table16DOS.size() > 0) {
                        UserBaseTable16DO table16DO = table16DOS.get(0);
                        BigDecimal pgj = table16DO.getValuationPrice();
                        BigDecimal mj = new BigDecimal(table16DO.getAreaOfStructure());
                        //评估价*建筑面积*X成-剩余本金=额度
                        BigDecimal ed = pgj.multiply(mj).multiply(accessDO.getPortions()).subtract(table16DO.getOddCorpus()).setScale(2, RoundingMode.HALF_UP);
                        ed = checkAmount(ed, accessDO.getMaxAmount());
                        ed = CalculateUtils.formatZeroMoney(ed);
                        accessDO.setQuotaFormula(ed);
                        m = CalculateUtils.getMonthCalculation(accessDO, ed.toString(), 0);
                    }
                }

                //提成
                if (percentageDO != null) {
                    if (percentageDO.getDeductType().equals("0")) {
                        accessDO.setUnits("元");
                        accessDO.setDeduct(percentageDO.getBusinessManagerRoyalty());
                        accessDO.setDirectProfit(percentageDO.getDirectProfit());
                    } else if (percentageDO.getDeductType().equals("1")) {
                        accessDO.setUnits("%");
                        accessDO.setDeduct(percentageDO.getBusinessManagerRoyalty());
                        accessDO.setDirectProfit(percentageDO.getDirectProfit());
                    }
                    //PercentageVO percentageVO = CalculateUtils.getDeduct(percentageDO,accessDO.getQuotaFormula());
                    //accessDO.setDeduct(percentageVO.getBusinessManagerRoyalty());
                }

                //月供
                if (m.size() > 0) {
                    accessDO.setMonthlyInfo(m.get(0));
                }
                doList.add(accessDO);

                //额度2-方案
                if (m.size() > 1) {
                    ProductAccessDO productAccessDO = new ProductAccessDO();
                    BeanUtils.copyProperties(accessDO, productAccessDO);
                    productAccessDO.setQuotaFormula(new BigDecimal(str[1].replace(",", "")));
                    //月供方案2
                    productAccessDO.setMonthlyInfo(m.get(1));
                    //提成
                    if (percentageDO != null) {
                        if (percentageDO.getDeductType().equals("0")) {
                            accessDO.setUnits("元");
                            accessDO.setDeduct(percentageDO.getBusinessManagerRoyalty());
                            accessDO.setDirectProfit(percentageDO.getDirectProfit());
                        } else if (percentageDO.getDeductType().equals("1")) {
                            accessDO.setUnits("%");
                            accessDO.setDeduct(percentageDO.getBusinessManagerRoyalty());
                            accessDO.setDirectProfit(percentageDO.getDirectProfit());
                        }
                    }
                    doList.add(productAccessDO);
                }

            }
        }

        return doList;
    }

    @Override
    public void dbUpdateUser(UserInfoDbVO vo) {
        UserDO user = new UserDO();
        BeanUtils.copyProperties(vo, user);
        if (StringUtils.isNotEmpty(vo.getPassword())) {
            user.setPassword(encodePassword(vo.getPassword())); // 加密密码
        }
        String customLable = "";
        if (vo.getCustomLabelArr() != null) {
            if (vo.getCustomLabelArr().length > 0) {
                for (String s : vo.getCustomLabelArr()) {
                    customLable += s.toString() + ",";
                }
                customLable = customLable.replaceFirst(",$", "");
            }
        }

        user.setCustomLabel(customLable);
        miniUserMapper.updateById(user);
    }


    @Override
    public boolean getCheckFinanceFlag() {
        boolean flag = false;
        String values = housingResourceMapper.getSslURL("mini.flag.key");
        if (StringUtils.isNotEmpty(values)) {
            if (values.equals("true")) {
                flag = true;
            }
        }
        return flag;
    }


    /**
     * 判断一个实体类对象实例的所有成员变量是否为空
     *
     * @param obj 校验的类对象实例
     * @return List
     * @throws Exception
     */

    public static List<String> isObjectFieldEmpty(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();  //得到类对象
        Field[] fs = clazz.getDeclaredFields(); //得到属性集合
        List<String> list = new ArrayList<String>();
        for (Field field : fs) {            //遍历属性
            field.setAccessible(true); //设置属性是可以访问的（私有的也可以）
            if (field.get(obj) == null || field.get(obj) == "" || "null".equalsIgnoreCase(field.get(obj).toString())) {
                String name = (String) field.getName();
                list.add(name);
            }
        }
        return list;
    }

    public static BigDecimal checkAmount(BigDecimal amount, BigDecimal max) {
        if (max == null) {
            return amount;
        }
        ////大于一百万则最高一百万
        if (amount.compareTo(max) == 1) {
            return max;
        } else { //否则返回原来额度
            return amount;
        }
    }

    public static double convertWanToYuan(String amountInWan) {
        double wan = Double.parseDouble(amountInWan);
        return wan * 10000;
    }


}
